7.7 複数行にまたがるテキストの検索

この節では、NとDコマンドを使って、複数行にまたがる連続した単語を検索します。複数行を扱う手法:D,G,H,N,Pによる複数行の処理を参照してください。

ここでは、文書内で同じ単語が続けて2回現れる箇所を探す例を扱います。

1行の中で重複する単語は、GNU grepで簡単に見つけられます。GNU sedでも同様です。

$ cat two-cities-dup1.txt
It was the best of times,
it was the worst of times,
it was the the age of wisdom,
it was the age of foolishness,

$ grep -E '\b(\w+)\s+\1\b' two-cities-dup1.txt
it was the the age of wisdom,

$ grep -n -E '\b(\w+)\s+\1\b' two-cities-dup1.txt
3:it was the the age of wisdom,

$ sed -En '/\b(\w+)\s+\1\b/p' two-cities-dup1.txt
it was the the age of wisdom,

$ sed -En '/\b(\w+)\s+\1\b/{=;p}' two-cities-dup1.txt
3
it was the the age of wisdom,

重複する単語が2行にまたがる場合、上の正規表現では見つかりません。grepとsedは1行ずつ処理するためです。

NとDコマンドを使えば、sedで複数行に正規表現を適用できます(つまり、複数行をパターンスペースに格納し、それに対して正規表現を適用します)。

$ cat two-cities-dup2.txt
It was the best of times, it was the
worst of times, it was the
the age of wisdom,
it was the age of foolishness,

$ sed -En '{N; /\b(\w+)\s+\1\b/{=;p} ; D}'  two-cities-dup2.txt
3
worst of times, it was the
the age of wisdom,

tr -sとuniqを使う別の解法については、GNU coreutilsマニュアルのhttps://gnu.org/s/coreutils/manual/html_node/Squeezing-and-deleting.htmlを参照してください。