如何在bash脚本中用逗号分割列表 [英] How to split a list by comma in bash script
问题描述
我试图读取csv
文件并用逗号分割数据.
I was trying to read a csv
file and split the data by comma.
我用过
IFS=, list=($line)
for word in ${list[@]}; do
echo $word
done
根据逗号分割csv
记录,效果很好.
to split the csv
record based on comma, which works fine.
问题是,我在csv中有一个带引号的字符串,其中包含逗号
The issue is when I have a quoted string in the csv which contains a comma
Name, "Oct 2, 2015 at 1:06 PM", Superman
在这种情况下,它返回
Name
"Oct 2
2015 at 1:06 PM"
Superman
我要
Name
"Oct 2, 2015 at 1:06 PM"
Superman
如何解决这个问题?
推荐答案
在纯bash中没有很好的方法来执行此操作,并且您不能使用cut
来执行此操作,这也不尊重引号.
There isn't a good way to do this in pure bash, and you can't use cut
to do it, which also doesn't respect quotes.
尽管如此,周围也有不错的命令行实用程序.例如,Fedora有一个csv
软件包,它提供一个csv
命令,该命令执行与cut
相同的操作,但要遵守引号:
There are good command-line utilities around that do it, though. Fedora has a csv
package, for instance, that provides a csv
command that does the same sort of thing as cut
but respecting quotes:
[james@marlon ~] $ echo '1,"3,w",4' | csv --col 2
"3,w"
它还提供了一个软件包ocaml-csv
,它为您提供了具有相似功能的csvtool
:
It also provides a package ocaml-csv
, which gives you csvtool
with similar functionality:
[james@marlon ~] $ echo '1,"3,w",4' | csvtool col 2 -
"3,w"
这些也很有可能在其他发行版中提供.
These are very likely to be available on other distros too.
这篇关于如何在bash脚本中用逗号分割列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!