2016-09-16 172 views
1

我有20K + IP地址在這個文件中:拆分逗號分隔字符串中的Bash

104.20.15.220,104.20.61.219,104.20.62.219,104.20.73.221,104.20.74.221,104.20.14.220 
104.20.15.220,104.20.73.221,104.20.74.221,104.25.195.107,104.25.196.107,104.20.14.220 
91.215.154.209 
... 

的問題是如何分成單個IP地址上的每個字符串:

104.20.15.220 
104.20.61.219 

回答

8

只是這些命令的更換新線逗號:

tr ',' '\n' < file 

sed 's/,/\n/g' file 

perl 's/,/\n/g' file 

awk 'gsub(/,/,"\n")' file 

...或文本高達每塊匹配逗號或行尾:

grep -oP '.*?(?=,|$)' file 

...或廁所通過場p和打印出來:

awk -F, '{for(i=1;i<=NF;i++) print $i}' file 

...或記錄分隔符設置爲逗號,讓awk做所有的工作:

awk -v RS=, '1' file 
awk 1 RS=, file 

...或匹配的IP地址,你可以使用正則表達式從Matching IPv4 Addresses

grep -oE '((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)' file 

他們全部迴歸:

104.20.15.220 
104.20.61.219 
104.20.62.219 
104.20.73.221 
... 
+1

最後awk命令是真棒 –

+1

如果你想使它更短,你可以去'AWK 1 RS =,file' –

+1

可以添加一些更多的方式:??'grep的-OP」 *(= ,| $)'','grep -oP'(\ d {1,3} \。){3} \ d {1,3}'','perl -pe's /,/ \ n/g' '等等:) – Sundeep

2

這將改變所有的命令進入換行。

tr ',' '\n' <filename 

awk 'BEGIN{FS=",";OFS="\n"}{$1=$1}1' filename