如何迭代以逗号分隔的文件?
我尝试了以下方法:
$ cat file | tr ',' '\n' > /tmp/f1
$ while read -r line;do
echo $line;
done < /tmp/f1
如何在不创建临时文件的情况下迭代第一行内容?
有任何想法吗?
答案1
首先,避免使用 shell 循环进行文本解析。这很难做到,很容易出错,而且很难阅读。而且很慢。非常非常慢。相反,使用awk
专门设计用于按“字段”读取的内容。例如,使用此输入文件:
foo, bar, baz
oof, rab, zab
awk -F,
您可以使用将字段分隔符设置为 来读取每个逗号分隔的字段,
:
$ awk -F, '{ print "The 1st field is",$1,"the 2nd", $2,"and the 3rd", $3}' file
The 1st field is foo the 2nd bar and the 3rd baz
The 1st field is oof the 2nd rab and the 3rd zab
即使您坚持在 shell 中执行此操作,您也不需要临时文件,也不需要tr
.您可以告诉while read
以逗号分隔:
$ while IFS=, read -r one two three; do
echo "The 1st field is $one, the 2nd $two and the 3rd $three";
done < file
The 1st field is foo, the 2nd bar and the 3rd baz
The 1st field is oof, the 2nd rab and the 3rd zab
答案2
csv 文件中的字段可能跨越多行,出于这个原因和其他原因,这就是我更喜欢使用的原因xsv当我必须解析 csv 时。
使用 bash 和 xsv 解析 csv 文件的一种方法是:
csvFile="myfile.csv"
lengthItems=$((($(xsv count "$csvFile") - 1 ))) # -1 because for loop start at 0
for i in $( seq 0 "$lengthItems" ); do
row="$(xsv slice -i "$i" "$csvFile")" # real magic happening here
# Do what you want with your $row here
done