【问题标题】:how can I find two consecutive lines having the the same pattern如何找到具有相同模式的两条连续线
【发布时间】:2015-11-20 16:16:57
【问题描述】:

我的文本文件如下所示:

bla : 1 - etc
blb : a - etc
blc : 2 - etc
bld : 3 - etc
ble : 1 - etc
blf : 1 - etc
blg : a - etc
blh : 1 - etc
bli : a - etc

我正在文件中搜索模式": 1 -"。一些连续的行具有相同的模式,我需要这两行加上下一行。

ble : 1 - etc
blf : 1 - etc
blg : a - etc

是否可以使用grepsed 或任何其他工具提取这些行? 提前致谢。

【问题讨论】:

  • 不清楚你在这里的意思。请edit说的更清楚

标签: awk sed grep


【解决方案1】:

这是一个使用 awk 的相当简单的任务:

awk -F ' [:-] ' '
    $2 == prev2 {        # if the 2nd field matches the previous 2nd field,
        print prevline   #   print the previous line
        print            #   print the current line
        getline; print   #   get the next line and print it
    } 
    {prev2 = $2; prevline = $0}  # remember these values for the next iteration
' file

【讨论】:

    【解决方案2】:

    我会使用awk 而不是sed

    awk -F: 'm~$2{print m;print;getline;print}{m=$0}' input.txt
    

    m 是一个保存最后一行的变量。如果它与: 后面的部分匹配,我们打印m 和当前行,然后获取下一行并打印它。最后m=$0将当前行存储在m中。

    【讨论】:

      【解决方案3】:

      Awk 比 sed 更适合像“if”这样的逻辑结构。

      $ awk 'substr($0,4,5)==last{print lastline;print;getline;print;} {last=substr($0,4,5);lastline=$0;}' input.txt
      ble : 1 - etc
      blf : 1 - etc
      blg : a - etc
      

      我假设你知道你需要什么,而不是用空格分隔的字段来分割你的行,: 1 - 确实是你正在寻找的。如果您的输入数据与您的示例不匹配,请随时进行更正。

      【讨论】:

        【解决方案4】:

        你可以使用 egrep:

        egrep -A2 ": 1 -" filename
        

        其中 A2 显示找到模式后的下两行。

        输出:

        bla : 1 - etc
        blb : a - etc
        blc : 2 - etc
        --
        ble : 1 - etc
        blf : 1 - etc
        blg : a - etc
        blh : 1 - etc
        bli : a - etc
        

        【讨论】:

        • 你建议 OP 寻找什么模式?
        【解决方案5】:

        是的,awk:

        awk '/: 1 -/  {++i}
             i>1      {print p}
             !/: 1 -/ {if(i>1)print;i=0}
                      {p=$0}
             END      {if(i>1)print p}'
        

        【讨论】:

          【解决方案6】:
          awk '$1 ~/^bl$|e|f|g/' file
          ble : 1 - etc
          blf : 1 - etc
          blg : a - etc
          

          如果第一列以 bl 开头并以 e、f 或 g 结尾,则打印这些行。

          【讨论】:

            【解决方案7】:
            awk '/: 1 -/ {CNT++; x[CNT]=$0; next} CNT==2 {print x[1]; print x[2]; print $0} {CNT=0}' *.*
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2017-01-17
              • 2018-12-16
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多