Grep最后一场比赛的前后 [英] Grep after and before lines of last Match

查看:64
本文介绍了Grep最后一场比赛的前后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在搜索一些日志,我想重复一下最后一行以及它在上下几行之间.

I am searching through few logs and I want to grep the last match along with it's above and below few lines.

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

grep -A10 -B10 "searchString" my.log will print all the matches with after and before 10 lines grep "searchString" my.log | tail -n 1 will print the last match.

我想将两者结合起来,以获得最后一场比赛的前十行和后十行.

I want to combine both and get the after and before 10 lines of last match.

推荐答案

如果您希望同时执行所有命令,请尝试以下awk

If you like to have all in one command, try this 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

用于处理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

这篇关于Grep最后一场比赛的前后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆