假設我有這樣的文字如何顯示在第二個正則表達式匹配的sed
The code for 233-CO is the main reason for 45-DFG and this 45-GH
現在我有這個正則表達式\s[0-9]+-\w+
其中233-CO
,45-DFG
和45-GH
匹配。
我該如何顯示第三場比賽45-GH
?
sed -re 's/\s[0-9]+-\w+/\3/g' file.txt
其中\3
應該是第三次正則表達式匹配。
假設我有這樣的文字如何顯示在第二個正則表達式匹配的sed
The code for 233-CO is the main reason for 45-DFG and this 45-GH
現在我有這個正則表達式\s[0-9]+-\w+
其中233-CO
,45-DFG
和45-GH
匹配。
我該如何顯示第三場比賽45-GH
?
sed -re 's/\s[0-9]+-\w+/\3/g' file.txt
其中\3
應該是第三次正則表達式匹配。
要找到你的模式的最後一個實例,您可以使用此:
$ sed -re 's/.*\s([0-9]+-\w+).*/\1/g' file
45-GH
是否必須使用sed
?你可以用grep
做到這一點,使用數組:
text="The code for 233-CO is the main reason for 45-DFG and this 45-GH"
matches=($(echo "$text" | grep -o -m 3 '\s[0-9]\+-\w\+')) # store first 3 matches in array
echo "${matches[0]} ${matches[2]}" # prompt first and third match
+1真的很好。 – Guru
如果AWK被接受,有一個awk onliner,你給你想抓住比賽的無#,它給你匹配的海峽。
awk -vn=$n '{l=$0;for(i=1;i<n;i++){match(l,/\s[0-9]+-\w+/,a);l=substr(l,RSTART+RLENGTH);}print a[0]}' file
測試
kent$ echo $STR #so we have 7 matches in str
The code for 233-CO is the main reason for 45-DFG and this 45-GH,foo 004-AB, bar 005-CC baz 006-DDD and 007-AWK
kent$ n=6 #now I want the 6th match
#here you go:
kent$ awk -vn=$n '{l=$0;for(i=1;i<=n;i++){match(l,/\s[0-9]+-\w+/,a);l=substr(l,RSTART+RLENGTH);}print a[0]}' <<< $STR
006-DDD
這可能爲你工作(GNU SED):
sed -r 's/\b[0-9]+-[A-Z]+\b/\n&\n/3;s/.*\n(.*)\n.*/\1/' file
s/\b[0-9]+-[A-Z]+\b/\n&\n/3
前插和追加\n
(新行)在第三(N)模式題。s/.*\n(.*)\n.*/\1/
模式之前和之後刪除文本隨着grep
進行匹配和sed
打印發生:
$ egrep -o '\b[0-9]+-\w+' file | sed -n '1p'
233-CO
$ egrep -o '\b[0-9]+-\w+' file | sed -n '2p'
45-DFG
$ egrep -o '\b[0-9]+-\w+' file | sed -n '3p'
45-GH
還是有一點awk
傳遞發生使用變量o
打印:
$ awk -v o=1 '{for(i=0;i++<NF;)if($i~/[0-9]+-\w+/&&j++==o-1)print $i}' file
233-CO
$ awk -v o=2 '{for(i=0;i++<NF;)if($i~/[0-9]+-\w+/&&j++==o-1)print $i}' file
45-DFG
$ awk -v o=3 '{for(i=0;i++<NF;)if($i~/[0-9]+-\w+/&&j++==o-1)print $i}' file
45-GH
您是否需要第三塊墊子特別是,還是最後一個?如果這種模式出現四次,你想要什麼? – Cozzamara
我的意思是有什麼辦法可以匹配任何編號的正則表達式。如果在該行中有7個,那麼'\ 7'應該返回匹配的第7個模式 – user1755071