如何在 bash 中迭代 CSV 檔案?

如何在 bash 中迭代 CSV 檔案?

如何迭代以逗號分隔的檔案?

我嘗試了以下方法:

$ 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

相關內容