Last active
June 2, 2019 15:12
-
-
Save ytez/a579cc01faab0ecfd4d1be5617795681 to your computer and use it in GitHub Desktop.
AWKで、$1, $2, ... $(NF) を配列に入れてみる (for @callmekohei)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/gawk -f | |
# for @callmekohei | |
BEGIN{ | |
# コンマ以外の1文字以上の連続 | |
# ないし、"以外の1文字以上の連続が""で囲われている | |
FPAT = "([^,]+|\"[^\"]+\")"; | |
} | |
{ | |
# 配列消去 (前の行の処理が残っているため) | |
delete arr | |
# $1, $2, ... $(NF) を 配列に代入する | |
# (配列の練習のためにわざわざやってます) | |
getarr_current_line(arr) | |
# 配列の要素数を出力 | |
printf("num of fields = %02d; ", length(arr)) | |
# " --> " 区切りで出力 | |
for(i = 1; i <= length(arr); i++) { | |
printf("%s%s", ((i==1) ? "" : " --> "), arr[i]) | |
} | |
# 末尾はきちんと改行 | |
print "" | |
} | |
# 現在処理している行 ($1, $2, ... $(NF)) を配列に代入する関数 | |
# 関数内で使用している end_pos, i はそのままだと Global 変数になってしまうため、 | |
# 引数内に書いておくことでローカル化する (少し離してわかりやすくする) | |
function getarr_current_line(arr, end_pos, i) { | |
end_pos = NF # フィールド数 | |
for(i = 1; i <= end_pos; i++) { | |
arr[i] = $(i) # arr[2] には $2 が入る | |
} | |
} | |
# 実行例 | |
# $ echo -e 'foo,"wilkinson,tansan",baz\nWe will,we will rock You' | ./getarr_current_line.awk | |
# num of fields = 03; foo --> "wilkinson,tansan" --> baz | |
# num of fields = 02; We will --> we will rock You |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment