【问题标题】:How can i grep from one point to another while ignoring the first match?我如何在忽略第一场比赛的情况下从一个点到另一个点?
【发布时间】:2020-01-14 17:17:09
【问题描述】:

我想从一个字符串 grep 到另一个字符串的第二次出现。 示例文件:

11111111
22222222
33333333
44444444
55555555
66666666
77777777
88888888
77777777
99999999

例如,我的第一个匹配项是“22222222”第二个匹配项是“77777777”的第二个匹配项 所以输出将是:

22222222
33333333
44444444
55555555
66666666
77777777
88888888
77777777

我知道我可以像这样使用 sed 从第一场比赛到第二场比赛:

sed -n -e '/22222222/,/77777777/ p'

但是我努力让它忽略第一个 77777777,我尝试添加 2,$, 但这给了我一个错误。 我怎样才能做到这一点?

【问题讨论】:

    标签: regex shell awk sed grep


    【解决方案1】:

    请您尝试关注一下。

    awk '$0==22222222{found1++} $0==77777777{found2++} found1;found2==2{exit}' Input_file
    

    说明:为上述代码添加详细说明。

    awk '             ##Starting awk program from here.
    $0==22222222{     ##Checking if line is 22222222 then do following.
      found1++        ##Creating variable found1 and keep increasing its value by 1 here.
    }                 ##Closing BLOCK for above condition here.
    $0==77777777{     ##Checking if line is 77777777 then do following.
      found2++        ##Creating variable found2 and keep increasing its value by 1 here.
    }                 ##Closing BLOCK for above condition here.
    found1            ##Checking condition if found1 variable is NOT NULL then it will print that line.
    found2==2{        ##Checking condition if variable found2 is equal to 2 then do following.
      exit            ##Using exit function of awk to exit from program since 2nd occurrence if found and NO need to read rest of the file.
    }
    ' Input_file      ##Mentioning Input_file name here.
    
    • 使用exit 将节省我们的时间;为什么,因为一旦发现第二次出现 77777777,就不需要读取 Input_file 的其余部分。

    【讨论】:

      猜你喜欢
      • 2022-11-23
      • 2016-06-05
      • 1970-01-01
      • 2012-03-27
      • 1970-01-01
      • 2020-10-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-25
      相关资源
      最近更新 更多