我试图用来grep
搜索一个大文本文件,并返回包含几个关键词的段落。我还想返回结果中周围的行。例如,我要搜索以下单词:蓝色、绿色、黄色。如果我想在名为“colors.txt”的文件中找到包含所有 3 个单词的段落,我尝试了以下代码:
grep blue colors.txt | grep green | grep yellow
但这只给了我黄色的列表,而不是段落中含有黄色、绿色和蓝色的列表。
然后我想显示周围的单词,所以使用了类似的东西
grep -B 5 blue colors.txt | grep green colors.txt
等等等等
总之 - 我有一个很大的文本文件,我想找到包含三种颜色的部分,但显示它周围的线条。
答案1
perl -00 -n -e 'print if (m/blue/i && m/green/i && m/yellow/i)' filename
这使用 的perl
段落阅读模式 ( -00
) 来仅打印包含所有三个单词的段落(不区分大小写的匹配)。
“段落”是一行或多行文本,与其他段落之间至少有一个空行分隔。
例如,我将您的问题文本保存到一个文件中,并perl
对其运行了这一行。输出是:
i am trying to use grep to search a large text file, and return the
paragraph containing a few key words. I also want to return the
surrounding lines in the result. So, for example I have the following
words I am going to search for: blue, green, yellow. If I wanted to find
the paragraph containing all 3 words, in the file called 'colors.txt', I
tried the following code:
grep blue colors.txt | grep green | grep yellow
This only gave me the listings for yellow though, and not the ones that
had yellow, green and blue, in the paragraph.
即只有 3 段输出,而你的问题有 7 段。