簡體   English   中英

在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM