我如何在每一条匹配的线周围显示前面和后面的5条线?


当前回答

让我们用一个例子来理解。我们可以使用带有选项的grep:

-A 5  # this will give you 5 lines after searched string.
-B 5  # this will give you 5 lines before searched string.
-C 5  # this will give you 5 lines before & after searched string

实例File.txt包含6行,以下是操作。

[abc@xyz]~/% cat file.txt # print all file data
this is first line
this is 2nd line
this is 3rd line
this is 4th line
this is 5th line
this is 6th line

[abc@xyz]~% grep "3rd" file.txt # we are searching for keyword '3rd' in the file
this is 3rd line

[abc@xyz]~% grep -A 2 "3rd" file.txt # print 2 lines after finding the searched string
this is 3rd line
this is 4th line
this is 5th line

[abc@xyz]~% grep -B 2 "3rd" file.txt # Print 2 lines before the search string.
this is first line
this is 2nd line
this is 3rd line

[abc@xyz]~% grep -C 2 "3rd" file.txt # print 2 line before and 2 line after the searched string 
this is first line
this is 2nd line
this is 3rd line
this is 4th line
this is 5th line

记住选项的技巧:选项:

-一个 -> 之后的平均值-B级 -> B表示之前。-c类 -> 介于两者之间

其他回答

$ grep thestring thefile -5

-5会让你在匹配项上下各5行,“thestring”相当于-C 5或-A 5-B 5。

这是awk中的@Ygor解决方案

awk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=3 a=3 s="pattern" myfile

注意:用前后的行数替换a和b变量。

它对于不支持grep的-A、-B和-C参数的系统特别有用。

里普雷普

如果您关心性能,请使用与grep语法相似的ripgrep,例如。

rg -C5 "pattern" .

-C、 --context NUM—在每次匹配前后显示NUM行。

还有一些参数,如-A/-after上下文和-B/-before上下文。

该工具构建在Rust的正则表达式引擎之上,这使得它对大数据非常有效。

对于BSD或GNUgrep,可以使用-B num设置匹配前的行数,使用-A num设置匹配后的行数。

grep -B 3 -A 2 foo README.txt

如果希望前后行数相同,可以使用-C num。

grep -C 3 foo README.txt

这将显示前3行和后3行。

我通常使用

grep searchstring file -C n # n for number of lines of context up and down

许多像grep这样的工具也有很棒的man文件。我发现自己经常参考grep的手册页,因为你可以用它做很多事情。

man grep

许多GNU工具也有一个信息页,除了手册页之外,它可能还有更多有用的信息。

info grep