我如何在每一条匹配的线周围显示前面和后面的5条线?
当前回答
$ 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参数的系统特别有用。
ack使用与grep类似的参数,并接受-C。但它通常更适合于搜索代码。
我通常使用
grep searchstring file -C n # n for number of lines of context up and down
许多像grep这样的工具也有很棒的man文件。我发现自己经常参考grep的手册页,因为你可以用它做很多事情。
man grep
许多GNU工具也有一个信息页,除了手册页之外,它可能还有更多有用的信息。
info grep
里普雷普
如果您关心性能,请使用与grep语法相似的ripgrep,例如。
rg -C5 "pattern" .
-C、 --context NUM—在每次匹配前后显示NUM行。
还有一些参数,如-A/-after上下文和-B/-before上下文。
该工具构建在Rust的正则表达式引擎之上,这使得它对大数据非常有效。
使用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