简单的 bash CSV 数组问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17329747/
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
Simple bash CSV array issue
提问by Atomiklan
I'm trying to do something fairly simple, and I'm just coming up short. Here is an example variable I'm trying to work with:
我正在尝试做一些相当简单的事情,但我只是做空了。这是我正在尝试使用的示例变量:
20,80,443,53
The variable is just a string of ports separated by commas. I need to get those into an array.
该变量只是一串由逗号分隔的端口。我需要将它们放入一个数组中。
回答by iruvar
Set IFSto ,and use the read command with a here-string
设置IFS为,并使用带有 here-string 的 read 命令
IFS=, read -r -a arr <<<"20,80,443,53"
printf "%s\n" "${arr[@]}"
20
80
443
53
回答by Hai Vu
Here is one way:
这是一种方法:
#!/bin/bash
v="20,80,443,53"
IFS=, a=($v) # Split
echo ${a[0]} # Display
echo ${a[1]}
echo ${a[2]}
echo ${a[3]}
Update
更新
Thanks to gniourf_gniourf for pointing out that IFS was modified as the result of the assignment. Here is my quirkywork around. Now I see why others did things differently.
感谢 gniourf_gniourf 指出 IFS 被修改为赋值的结果。这是我古怪的工作。现在我明白了为什么其他人做事的方式不同。
v="20,80,443,53"
PREV_IFS="$IFS" # Save previous IFS
IFS=, a=($v)
IFS="$PREV_IFS" # Restore IFS
echo ${a[0]}
echo ${a[1]}
echo ${a[2]}
echo ${a[3]}
回答by glenn Hymanman
var="20,80,442,53"
IFS=, read -ra ary <<< "$var"
printf "%s\n" "${ary[@]}"
20
80
442
53
回答by user2448541
Ports=('20','80','443','53');
for e in "${lic4l[@]}"; do
echo $e
I hope this will help and print the ports in the given variable.
我希望这会有所帮助并打印给定变量中的端口。
回答by Eugene Wagner
With SED it becomes a one-liner:
使用 SED,它变成了单线:
a=($(sed 's/,/ /g' <<< "20,80,443,53"))
printf "%s\n" "${a[@]}"
20
80
443
53

