首页 > 解决方案 > 在bash脚本中第一次出现模式之前删除所有字符串

问题描述

所以我有问题。我想在找到某个模式之前删除文件的全部内容,但仅在第一次出现时删除。模式:(([0-9]{2}:[0-9]{2}:[0-9]{2}).([0-9]{6})它适合字符串的日期部分)。

比如这个内容:

-- 10:17:40.614568 00:00:00:00:00:00 > ff:ff:ff:ff:ff:ff, ethertype IPv4 (0x0800), length 303: (tos 0x0, ttl 64, id 0, offset 0, flags [DF], proto UDP (17), length 289) 0.0.0.0.68 > 255.255.255.255.67: BOOTP/DHCP, Request from 00:00:00:00:00:00, length 261, xid 0x1466f606, Flags [Broadcast]

应解析为:

10:17:40.614568 00:00:00:00:00:00 > ff:ff:ff:ff:ff:ff, ethertype IPv4 (0x0800), length 303: (tos 0x0, ttl 64, id 0, offset 0, flags [DF], proto UDP (17), length 289) 0.0.0.0.68 > 255.255.255.255.67: BOOTP/DHCP, Request from 00:00:00:00:00:00, length 261, xid 0x1466f606, Flags [Broadcast]

标签: bashawksedgrep

解决方案


编辑:由于 OP 提到只有在整个 Input_file 中的第一个正则表达式匹配才能满足条件,所以现在添加这个解决方案。

awk --re-interval '
match($0,/[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{6}/)  && !index{
  print substr($0,RSTART)
  index=1
  next
}
index ' Input_file


请您尝试以下操作。

awk --re-interval '
match($0,/[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{6}/){
  print substr($0,RSTART)
}' Input_file

它只会打印那些找到正则表达式匹配的行。如果您也想打印那些不匹配的行,请执行以下操作。

awk --re-interval '
match($0,/[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{6}/){
  print substr($0,RSTART)
  next
}
1' Input_file

因为我使用的是旧awk版本,所以我已经--re-interval删除它以防你上面的代码工作(awk它的新版本工作)

第一个代码的解释:

awk --re-interval '                                ##Starting awk program from here and --re-interval enables ERE for OLD versions of awk.
match($0,/[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{6}/){  ##Using match utility of awk here which will check REGEX provided to it either it presents on line or not.
  print substr($0,RSTART)                          ##match utility/function has variable named RSTART which denotes the starting of REGEX point, so I am using substring function to print from starting of that point to till end of line, since OP want to remove everything before REGEX match.
}
' Input_file                                       ##Mentioning Input_file name here.

对于第二个代码的解释将与第一个代码相同,唯一的区别是第二个代码next将跳过正则表达式匹配的行,1并将在 Input_file 中打印不匹配的行。


推荐阅读