在Bash中拆分逗号分隔的字符串

时间:2016-09-16 09:39:44

标签: bash

我的文件里面有20k + IP:

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

2 个答案:

答案 0 :(得分:10)

只需使用以下任一命令替换带有新行的逗号:

tr ',' '\n' < file

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

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

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

...或匹配每个文本块,直到逗号或行尾:

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

...或循环浏览字段并打印出来:

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 :(得分:2)

这会将所有命令转换为换行符。

tr ',' '\n' <filename

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