在Bash中用逗号分隔的字符串 [英] Split a comma separated strings in Bash

查看:79
本文介绍了在Bash中用逗号分隔的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文件中包含20k + IP:

I have this file with 20k+ IPs inside:

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:

The question is how to split in into single IPs on each string:

104.20.15.220
104.20.61.219

推荐答案

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

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

...或将记录分隔符设置为逗号,然后让 awk 完成所有工作:

... or set the record separator to the comma and let awk do all the work:

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

...或匹配IP,您可以使用匹配IPv4地址:

... or match the IPs, you can use the regex from 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
...

这篇关于在Bash中用逗号分隔的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆