我正在搜索一些日志,我想 grep 最后一个匹配项及其上方和下方的几行。
grep -A10 -B10 "searchString" my.log
将打印前后 10 行的所有匹配项grep "searchString" my.log | tail -n 1
将打印最后一个匹配项。
我想将两者结合起来并获得上一场比赛的前后 10 行。
如果您想将所有内容集中在一个命令中,请尝试此操作awk
awk '/search/ {f=NR} {a[NR]=$0} END {while(i++<NR) if (i>f-3 && i<f+3) print a[i]}' file
怎么运行的:
awk '
/search/ { # Is pattern found
f=NR} # yes, store the line number (it will then store only the last when all is run
{
a[NR]=$0} # Save all lines in an array "a"
END {
while(i++<NR) # Run trough all lines once more
if (i>f-3 && i<f+3) # If line number is +/- 2 compare to last found pattern, then
print a[i] # Printe the line from the array "a"
}' file # read the file
更灵活的解决方案来处理before
and after
awk '/fem/ {f=NR} {a[NR]=$0} END {while(i++<NR) if (i>=f-before && i<=f+after) print a[i]}' before=2 after=2 file
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)