在 Bash 中拆分逗号分隔的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39528273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Split a comma separated strings in Bash
提问by Vasiliy
I have this file with 20k+ IPs inside:
我有这个文件,里面有 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
...
The question is how to split in into single IPs on each string:
问题是如何在每个字符串上拆分为单个 IP:
104.20.15.220
104.20.61.219
回答by fedorqui 'SO stop harming'
Just replace a comma with a new line with either of these commands:
只需使用以下任一命令将逗号替换为新行:
tr ',' '\n' < file
sed 's/,/\n/g' file
perl 's/,/\n/g' file
awk 'gsub(/,/,"\n")' file
... or match every block of text up to a comma or the end of line:
...或匹配每个文本块直到逗号或行尾:
grep -oP '.*?(?=,|$)' file
... or loop through the fields and print them:
...或遍历字段并打印它们:
awk -F, '{for(i=1;i<=NF;i++) print $i}' file
... or set the record separator to the comma and let awk
do all the work:
...或将记录分隔符设置为逗号并让我们awk
完成所有工作:
awk -v RS=, '1' file
awk 1 RS=, file
... or match the IPs, you can use the regex from Matching IPv4 Addresses:
...或匹配 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
They all return:
他们都回来了:
104.20.15.220
104.20.61.219
104.20.62.219
104.20.73.221
...
回答by P....
This will transform all the commands into newline.
这会将所有命令转换为换行符。
tr ',' '\n' <filename
or
或者
awk 'BEGIN{FS=",";OFS="\n"}{=}1' filename