在 Ubuntu 中使用grep,我正在嘗試正則運算式匹配在一行中重復多次的模式。
例子:
0:0, 80:3, 443:0, 8883:0, 9000:0, 9001:0,
我嘗試的正則運算式是 -
([0-9] :[0-9] , )
但它只匹配 -
0:0, 80:3, 443:0, 8883:0, 9000:0,
我希望它與整行相匹配。另外,如果正則運算式將檢查匹配的字串中是否存在80和,我將不勝感激。443
期待 -
應匹配以下行 -
0:0, 80:3, 443:0, 8883:0, 9000:0, 9001:0,
0:0, 80:0, 443:1, 8883:0, 9000:0, 9001:0,
0:0, 80:0, 443:0, 8883:0, 9000:0, 9001:0,
0:0, 80:3, 443:1, 8883:0, 9000:0, 9001:0,
并且下面的不應該匹配 -
0:0, 443:0, 8883:0, 9000:0, 9001:0,
0:0, 80:0, 8883:0, 9000:0, 9001:0,
0:0, 8883:0, 9000:0, 9001:0,
uj5u.com熱心網友回復:
您可以使用
^[0-9] :[0-9] , 80:[0-9] , 443:[0-9] (, [0-9] :[0-9] ) ,$
請參閱正則運算式演示。
另外,考慮awk像這樣的解決方案
awk '/^[0-9] :[0-9] (, [0-9] :[0-9] ) ,$/ && /80/ && /443/' file
查看在線演示:
#!/bin/bash
s='0:0, 80:3, 443:0, 8883:0, 9000:0, 9001:0,
0:0, 80:0, 443:1, 8883:0, 9000:0, 9001:0,
0:0, 80:0, 443:0, 8883:0, 9000:0, 9001:0,
0:0, 80:3, 443:1, 8883:0, 9000:0, 9001:0,
0:0, 443:0, 8883:0, 9000:0, 9001:0,
0:0, 80:0, 8883:0, 9000:0, 9001:0,
0:0, 8883:0, 9000:0, 9001:0,'
awk '/^[0-9] :[0-9] (, [0-9] :[0-9] ) ,$/ && /80/ && /443/' <<< "$s"
輸出:
0:0, 80:3, 443:0, 8883:0, 9000:0, 9001:0,
0:0, 80:0, 443:1, 8883:0, 9000:0, 9001:0,
0:0, 80:0, 443:0, 8883:0, 9000:0, 9001:0,
0:0, 80:3, 443:1, 8883:0, 9000:0, 9001:0,
uj5u.com熱心網友回復:
這是更強大的awk模式匹配,根據您顯示的示例,在 GNU 中撰寫和測驗awk,應該可以在任何awk. 代碼的簡單解釋awk是:awk適用于condition/regexpthen的方法action,所以我在condition/regexp這里提到沒有任何操作,所以如果 regexp 為 TRUE(matched),那么默認情況下會列印行。
awk '/^0:[0-9],[[:space:]] 80:[0-9],[[:space:]] 443:[0-9],[[:space:]] 8883:[0-9](,[[:space:]] 9[0-9]{3}:[0-9]){2},$/' Input_file
說明:為上述正則運算式添加詳細說明。
^0:[0-9],[[:space:]] ##From starting of line matching 0 followed by colon followed by comma, followed y 0 OR 1 occurrences of space(s).
80:[0-9],[[:space:]] ##Above regex is followed by 80 colon any digit comma and space(s).
443:[0-9],[[:space:]] ##Above is followed by 443 colon digit comma and space(s).
8883:[0-9] ##Above is followed by 8883 followed by colon followed by any digit.
(,[[:space:]] 9[0-9]{3}:[0-9]){2} ##matching comma space(s) followed by 9 which is followed by 3 digits and this whole match 2 times(to match last 2 9000 etc values).
,$ ##Matching comma at the end of line here.
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/425679.html
