在最后一次匹配行之后和之前的 Grep

Red*_*ddy 7 search grep tail match

我正在搜索一些日志,我想 grep 最后一场比赛以及它在几行的上方和下方。

grep -A10 -B10 "searchString" my.log将打印前后 10 行的所有匹配项 grep "searchString" my.log | tail -n 1将打印最后一个匹配项。

我想将两者结合起来,得到最后一场比赛的前后 10 行。

Jot*_*tne 5

如果您想将所有内容集中在一个命令中,请尝试此操作awk

awk '/search/ {f=NR} {a[NR]=$0} END {while(i++<NR) if (i>f-3 && i<f+3) print a[i]}' file
Run Code Online (Sandbox Code Playgroud)

怎么运行的:

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
Run Code Online (Sandbox Code Playgroud)

更灵活的解决方案来处理beforeafter

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
Run Code Online (Sandbox Code Playgroud)