如何找到具有相同模式的两个连续行

时间:2015-11-05 15:59:01

标签: awk sed grep

我的文本文件如下:

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或任何其他工具提取此行? 提前谢谢。

7 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我会使用awk代替sed

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

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

答案 2 :(得分:0)

awk更适合像“if”这样的逻辑结构而不是sed。

$ 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 -确实是您正在寻找的东西,而不是按空格分隔的字段拆分您的行。如果您的输入数据与您的示例不符,请随时更正。

答案 3 :(得分:0)

你可以使用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

答案 4 :(得分:0)

是的,awk:

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

答案 5 :(得分:0)

awk '$1 ~/^bl$|e|f|g/' file
ble : 1 - etc
blf : 1 - etc
blg : a - etc

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

答案 6 :(得分:-1)

awk '/: 1 -/ {CNT++; x[CNT]=$0; next} CNT==2 {print x[1]; print x[2]; print $0} {CNT=0}' *.*
相关问题