如何根据模式输出特定段落?

如何根据模式输出特定段落?

我有一个示例文件如下:

# 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.

我需要输出从“#”开始到该段落最后一句的第二段。

如何根据模式 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表示段落模式(记录由一个或多个空行分隔)。

相关内容