[英]Get all strings after the 4th occurrence of the pattern is found in bash
[英]Removing all strings before first occurrence of a pattern in bash-script
所以我有一个问题。 我想在找到某种模式之前删除文件的全部内容,但是只在它第一次出现时才删除。 模式: ([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]
编辑:由于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
将其删除,以防上述代码对您--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中打印不匹配的行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.