bash - 在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]
解决方案
编辑:由于 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 中打印不匹配的行。
推荐阅读
- c++ - 避免信号处理程序线程中繁忙处理的选项?
- javascript - Nodejs 和 SQLite 如何创建多个表?
- flutter - 如何查看使用的是什么设备?
- laravel - 无法在公用文件夹 laravel 上存储图像上传
- javascript - javascript中文件的最后修改日期
- latex - PGFP 坐标轴刻度
- reactjs - .create() on mongoose 模式错误,“此表达式不可调用”-TypeScript
- javascript - 如何解决我的不和谐机器人遇到的这个错误
- linux-mint - 带有特殊字符的文件名的 Nemo 右键单击操作
- unity3d - Unity:Mesh Renderer 似乎并不完美地适合 Edge