p='[:punct:]' s='[:space:]'
sed -Ee'1!{/\n/!b' -e\} \
-e's/(\n*)(.*)/ \2 \1/' \
-e"s/is[$p]?[$s]/\n&/g" \
-e"s/([^$s])\n/\1/g;1G" \
-e:c -e"s/\ni(.* )\n{3}/u\1/" \
-e"/\n$/!s/\n//g;/\ni/G" \
-e's//i/;//tc' \
-e's/^ (.*) /\1/;P;$d;N;D'
そのビットは、ある行から次の行への発生のsed集計を運ぶだけisです。それはisあなたがそれに投げるのと同じくらい多くのesを行ごとに確実に処理するべきであり、それがそうしている間古い行をバッファリングする必要はありません-それisは別の単語の一部ではない遭遇するすべての単一の改行文字を保持するだけです。
その結果、ファイル内の3番目のオカレンスのみが変更され、1行あたりのカウントが含まれます。したがって、ファイルが次のようになっているとします。
1. is is isis
2. is does
...印刷されます...
1. is is isis
2. us does
まず、すべての行の先頭と末尾にスペースを挿入して、エッジケースを処理します。これにより、単語の境界が少しわかりやすくなります。
次にis、\nすべての出現箇所isが0個または1個の句読文字の直後にスペースが続く前に、ewlineを挿入して有効なesを探します。別のパスを\n実行し、スペース以外の文字が直前にあるすべてのewlineを削除します。残されたこのマーカーが一致するis.とisはありませんthisか?is。
次に、各マーカーを文字列の末尾に集めます。\ni行が一致するたび\nに、文字列の末尾にewlineが追加され、iまたはに置き換えられますu。\n文字列の末尾に集められた3つのewlinesが連続している場合は、uを使用します。それ以外の場合はiを使用します。auが最初に使用されたときも最後です-置換により、無限ループが発生get line, print line, get line, print line,します。
各tryループサイクルの最後に、挿入されたスペースをクリーンアップし、パターンスペースで最初に出現する改行までのみを印刷してから、再度実行します。
次のlように、ループの先頭にookコマンドを追加します。
l; s/\ni(.* )\n{9}/u\1/...
...そして、この入力で機能するときに何が行われるかを確認します。
hai this is linux.
hai this is unix.
hai this is mac.
hai this is unchanged is.
...だからここにそれが何をするかです:
hai this \nis linux. \n$ #behind the scenes
hai this is linux. #actually printed
hai this \nis unix. \n\n$ #it builds the marker string
hai this is unix.
\n\n\n$ #only for lines matching the
\n\n\n$ #pattern - and not otherwise.
hai this \nis mac. \n\n\n$ #here's the match - 3 ises so far in file.
hai this us mac. #printed
hai this is unchanged is. #no look here - this line is never evaled
is1行あたりのes が多ければ多いほど意味があります。
nthword()( p='[:punct:]' s='[:space:]'
sed -e '1!{/\n/!b' -e\} \
-e 's/\(\n*\)\(.*\)/ \2 \1/' \
-e "s/$1[$p]\{0,1\}[$s]/\n&/g" \
-e "s/\([^$s]\)\n/\1/g;1G;:c" \
-e "${dbg+l;}s/\n$1\(.* \)\n\{$3\}/$2\1/" \
-e '/\n$/!s/\n//g;/\n'"$1/G" \
-e "s//$1/;//tc" -e 's/^ \(.*\) /\1/' \
-e 'P;$d;N;D'
)
これは実質的に同じことですが、POSIX BREと基本的な引数処理を使用して記述されています。
printf 'is is. is? this is%.0s\n' {1..4} | nthword is us 12
...取得...
is is. is? this is
is is. is? this is
is is. is? this us
is is. is? this is
...そして私が有効にした場合${dbg}:
printf 'is is. is? this is%.0s\n' {1..4} |
dbg=1 nthword is us 12
...それが繰り返されるのを見ることができます...
\nis \nis. \nis? this \nis \n$
is \nis. \nis? this \nis \n\n$
is is. \nis? this \nis \n\n\n$
is is. is? this \nis \n\n\n\n$
is is. is? this is
\nis \nis. \nis? this \nis \n\n\n\n\n$
is \nis. \nis? this \nis \n\n\n\n\n\n$
is is. \nis? this \nis \n\n\n\n\n\n\n$
is is. is? this \nis \n\n\n\n\n\n\n\n$
is is. is? this is
\nis \nis. \nis? this \nis \n\n\n\n\n\n\n\n\n$
is \nis. \nis? this \nis \n\n\n\n\n\n\n\n\n\n$
is is. \nis? this \nis \n\n\n\n\n\n\n\n\n\n\n$
is is. is? this \nis \n\n\n\n\n\n\n\n\n\n\n\n$
is is. is? this us
is is. is? this is