我如何在每一条匹配的线周围显示前面和后面的5条线?
当前回答
使用grep
$ grep --help | grep -i context
Context control:
-B, --before-context=NUM print NUM lines of leading context
-A, --after-context=NUM print NUM lines of trailing context
-C, --context=NUM print NUM lines of output context
-NUM same as --context=NUM
其他回答
Grep有一个名为Context Line Control的选项,您可以使用--Context,
| grep -C 5
or
| grep -5
应该会成功的
对于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 astring myfile -A 5 -B 5
这将grep“myfile”表示“跨步”,并在每次比赛前后显示5行
如果您经常搜索代码,AG银搜索器比grep更高效(即更快)。
使用-C选项显示上下文行。
Eg:
ag -C 3 "foo" myFile
line 1
line 2
line 3
line that has "foo"
line 5
line 6
line 7
这是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参数的系统特别有用。