bash で CSV ファイルを反復処理する方法は?

bash で CSV ファイルを反復処理する方法は?

値がコンマで区切られたファイルを反復処理するにはどうすればよいでしょうか?

次のことを試しました:

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

一時ファイルを作成せずに最初の行の内容を反復処理するにはどうすればよいですか?

何か案は?

答え1

初めに、シェルループによるテキスト解析を避ける実行が難しく、間違いやすく、非常に読みにくいです。そして、遅いです。非常に遅いです。代わりに、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

シェルで実行する必要がある場合でも、一時ファイルは必要ありませんし、 も必要ありません。カンマで区切るように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ファイルのフィールドは複数行にまたがる可能性があるため、この理由とその他の理由から、私は翻訳csv を解析する必要があったとき。

bash と xsv を使用して csv ファイルを解析する 1 つの方法は次のとおりです。

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

関連情報