![パターンに応じて特定の段落を出力する方法は? [コピー]](https://linux33.com/image/95051/%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3%E3%81%AB%E5%BF%9C%E3%81%98%E3%81%A6%E7%89%B9%E5%AE%9A%E3%81%AE%E6%AE%B5%E8%90%BD%E3%82%92%E5%87%BA%E5%8A%9B%E3%81%99%E3%82%8B%E6%96%B9%E6%B3%95%E3%81%AF%EF%BC%9F%20%5B%E3%82%B3%E3%83%94%E3%83%BC%5D.png)
次のサンプルファイルがあります。
# This is a test file. This is a test file. This is a test file
This is a test file. This is a test file. This is a test file.
This is a test file.
# Need to output just this paragraph.Need to output just this paragraph.
Need to output just this paragraph TOO. Need to output just this paragraph.
Need to output just this paragraph.
「#」から始まり、段落の最後の文まで2番目の段落を出力する必要があります。
パターンに基づいてgrepして出力する方法は?ファイルにさらに段落があると仮定すると、「TOO」という単語を含む段落を出力したいと思います。
答え1
段落が空行で区切られた場合:
awk -v RS= -v ORS='\n\n' /TOO/
空のレコード区切り記号(RS
)は、次のことを意味します。短絡モードここで、レコードは一連の空行に分かれています。
分離された場合#
:
awk -v RS='#' '/TOO/ {print RS $0}'
または
pcregrep -Mo '#[^#]*?TOO[^#]*'
-M
複数行の場合grep
-o
一致する部分のみ出力
答え2
perl -00ne 'print if /TOO/'
-00
短絡モード(1つ以上の空行で区切られたレコード)を示します。