Shell-Script

如何在 bash 中迭代 CSV 文件?

  • May 16, 2022

如何迭代以逗號分隔的文件?

我嘗試了以下方法:

$ cat file | tr ','  '\n' > /tmp/f1
$ while read -r line;do 
  echo $line;
done < /tmp/f1

如何在不創建臨時文件的情況下迭代第一行內容?

有任何想法嗎?

首先,避免使用 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

引用自:https://unix.stackexchange.com/questions/554595