2016-05-04 58 views
1

請問任何機構請告訴我如何在bash中的這個內容中獲取所有ipv4地址(在「()」中)?如何獲取此內容中的所有ipv4地址

traceroute to 223.5.5.5 (223.5.5.5), 30 hops max, 60 byte packets 
1 1.2-88-23.rdns.scalabledns.com (23.88.2.1) 0.388 ms 0.404 ms 0.415 ms 
2 dist01-dc03-core.dc08.lax.ip4.scalabledns.com (172.246.0.235) 0.273 ms 18.825 ms 0.247 ms 
3 207.254.184.97 (207.254.184.97) 0.660 ms 0.771 ms 0.834 ms 
4 199.102.95.6 (199.102.95.6) 0.836 ms 0.808 ms 0.782 ms 
5 219.158.30.53 (219.158.30.53) 192.201 ms 192.186 ms 192.160 ms 
6 219.158.97.17 (219.158.97.17) 168.116 ms 168.193 ms 168.153 ms 
.... 

結果應該是這樣的

223.5.5.5 
23.88.2.1 
172.246.0.235 
.... 

非常感謝幫助我!

回答

3

此grep的線適用於你的例子:

grep -Po '.*\(\K[^)]*' file 

它輸出:

223.5.5.5 
23.88.2.1 
172.246.0.235 
207.254.184.97 
199.102.95.6 
219.158.30.53 
219.158.97.17 
0

grep與PCRE(-P):

​​3210

實施例:

在bash
$ cat file.txt 
traceroute to 223.5.5.5 (223.5.5.5), 30 hops max, 60 byte packets 
1 1.2-88-23.rdns.scalabledns.com (23.88.2.1) 0.388 ms 0.404 ms 0.415 ms 
2 dist01-dc03-core.dc08.lax.ip4.scalabledns.com (172.246.0.235) 0.273 ms 18.825 ms 0.247 ms 
3 207.254.184.97 (207.254.184.97) 0.660 ms 0.771 ms 0.834 ms 
4 199.102.95.6 (199.102.95.6) 0.836 ms 0.808 ms 0.782 ms 
5 219.158.30.53 (219.158.30.53) 192.201 ms 192.186 ms 192.160 ms 
6 219.158.97.17 (219.158.97.17) 168.116 ms 168.193 ms 168.153 ms 

$ grep -Po '\(\K[^)]+(?=\))' file.txt 
223.5.5.5 
23.88.2.1 
172.246.0.235 
207.254.184.97 
199.102.95.6 
219.158.30.53 
219.158.97.17 
0
$ sed 's/.*(\([^)]*\).*/\1/' file 
223.5.5.5 
23.88.2.1 
172.246.0.235 
207.254.184.97 
199.102.95.6 
219.158.30.53 
219.158.97.17 
0

一個行腳本(在bash基本知識就足夠了) http://www.tldp.org/LDP/abs/html/string-manipulation.html

# while read l;do expr "$l" : ".*(\(.*\))";done <your_trc_file 
223.5.5.5 
23.88.2.1 
172.246.0.235 
207.254.184.97 
199.102.95.6 
219.158.30.53 
219.158.97.17 

更多的解釋:

# while read l;do echo "$l";done <file ## read lines from a file 

# # Matching with reg-exp by 'exp :' command 
# expr "abcXdefghXXijk" : ".*X.*XX"  ## return length 
11 

# expr "abcXdefghXXijk" : ".*X\(.*\)XX" ## return extract 
defgh 
+0

儘管這段代碼可以回答這個問題,提供 關於_why_和/或_how_的附加上下文會回答 這個問題會顯着提高證明其長期價值 。請[編輯]你的答案,添加一些解釋。 –