awk, sed で csvファイルの処理


はじめに

CSVファイルをもとにテキストを処理したいこともあります。今回はその例です。

awk, sed

CSVファイルの内容が以下です。

csv
Satoh Taro, [email protected], 123
Suzuki Hana, [email protected], 124

出力させたい内容が以下です。Javaプログラムで使います。

put
put("[email protected]","123");
put("[email protected]","124");

実行させる内容

  • 2, 3 列目のみで 区切り文字 , を "," に変更
  • 最初に put("
  • 最後に ");

それぞれを実行させて以下のようになります。

awk,sed
$ cat test.txt 
Satoh Taro, [email protected], 123
Suzuki Hana, [email protected], 124
$ cat test.txt | awk 'BEGIN {FS=", ";OFS=","} {print $2,$3}'
[email protected],123
[email protected],124
$ cat test.txt | awk 'BEGIN {FS=", ";OFS="\",\""} {print $2,$3}'
[email protected]","123
[email protected]","124
$ cat test.txt | awk 'BEGIN {FS=", ";OFS="\",\""} {print $2,$3}' | sed "s/^/put(\"/"
put("[email protected]","123
put("[email protected]","124
$ cat test.txt | awk 'BEGIN {FS=", ";OFS="\",\""} {print $2,$3}' | sed "s/^/put(\"/" | sed "s/\$/\");/"
put("[email protected]","123");
put("[email protected]","124");

$ cat test.txt | awk 'BEGIN {FS=", ";OFS=","; print "Begin"} {print $2,$3} END {print "End"}'
Begin
[email protected],123
[email protected],124
End
$ echo "[email protected], [email protected]" | sed "s/@sample.com/@qiita.com/"
[email protected], [email protected]
$ echo "[email protected], [email protected]" | sed "s/@sample.com/@qiita.com/g"
[email protected], [email protected]

awk のポイント
BEGIN - 最初の行を読み込む前に実行
END - 最後の行を読み込んだ後に実行
FS - Field Separator 読み込み時の separator
OFS - Output Field Separator 出力時の separator

sed
s - 置換
g - 1行中のすべてのパターンに対して実行 (指定がなければ1行中の一致した最初のパターンのみ) 今回は g 必要なし

参考

【 awk 】コマンド(基本編その3)――テキストの加工とパターン処理・BEGIN・ENDとAWKスクリプト:Linux基本コマンドTips(117) - @IT
【 awk 】コマンド(応用編その3)――テキストの加工とパターン処理、配列の活用:Linux基本コマンドTips(209) - @IT
【 sed 】コマンド(基礎編その4)――文字列を置き換える/置換した行を出力する:Linux基本コマンドTips(56) - @IT