LoginSignup
2
1

More than 5 years have passed since last update.

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

Posted at

はじめに

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

awk, sed

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

csv
Satoh Taro, taro@sample.com, 123
Suzuki Hana, hana@sample.com, 124

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

put
put("taro@sample.com","123");
put("hana@sample.com","124");

実行させる内容

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

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

awk,sed
$ cat test.txt 
Satoh Taro, taro@sample.com, 123
Suzuki Hana, hana@sample.com, 124
$ cat test.txt | awk 'BEGIN {FS=", ";OFS=","} {print $2,$3}'
taro@sample.com,123
hana@sample.com,124
$ cat test.txt | awk 'BEGIN {FS=", ";OFS="\",\""} {print $2,$3}'
taro@sample.com","123
hana@sample.com","124
$ cat test.txt | awk 'BEGIN {FS=", ";OFS="\",\""} {print $2,$3}' | sed "s/^/put(\"/"
put("taro@sample.com","123
put("hana@sample.com","124
$ cat test.txt | awk 'BEGIN {FS=", ";OFS="\",\""} {print $2,$3}' | sed "s/^/put(\"/" | sed "s/\$/\");/"
put("taro@sample.com","123");
put("hana@sample.com","124");

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

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

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1