错误时打印上一个实际和下一个记录

时间:2018-11-13 15:22:26

标签: awk

在下面的示例中,在第2列中,值是递增的,然后的目的是获取不按升序排列的记录并打印(上一个-错误-下一个)

文件

2343 290232732   
2343 290232738   
2349 290202757   
2342 290232758   
2343 290232813   
2341 291063213   
2343 291043555   
2345 291063609   
2343 291063622   
2343 291063637   
2341 291053637   
2343 291063702   
2343 291063707   
2343 291063712   
2343 291063751

我尝试过

awk '{                                                                                                                               
         if(substr($0,6,9) < prev -1)                                                                                                                        
         {printf ("** ERROR ** %4d --> %4d --> %4d\n",prv2, prev, substr($0,6,9)) } ; prv2 = prev; prev = substr($0,6,9)}'  file

如何添加; 退出1 到代码,以便在找到最后一个错误后停止该过程。

我知道了

** ERROR ** 290232732 --> 290232738 --> 290202757
** ERROR ** 290232813 --> 291063213 --> 291043555
** ERROR ** 291063622 --> 291063637 --> 291053637

所需的输出

** ERROR ** 290232738 --> 290202757 --> 290232758
** ERROR ** 291063213 --> 291043555 --> 291063609
** ERROR ** 291063637 --> 291053637 --> 291063702

预先感谢

1 个答案:

答案 0 :(得分:1)

您可以尝试这个awk:

awk '
  f {                           # if flag print ERROR
    p = p FS "-->" FS $2
    print "** ERROR **" FS p
    split ( p , a )             # keep $2 of previous line in p
    p = a[3]                    # this way if it is in error you can catch it
    f = 0                       # remove flag
  }
  $2 > p {                      # $2 is ok keep it
    p = $2
    next
  }
  {
    p = p FS "-->" FS $2        # $2 is not ok
    f = 1                       # prepare to print
  }
  END {
    if ( f )                    # the last line is in error
      print "** ERROR **" FS p  # print it
  }
' file