awkは効率的にテキスト処理を行うことができます。
[vagrant@localhost awk]$ awk --version
GNU Awk 3.1.7
Copyright (C) 1989, 1991-2009 Free Software Foundation.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
本プログラムは、利用価値があることを期待して配布されていますが、
これは、特定目的に使用可能であること、及び、商用目的に使用できる
ことを暗示するものではなく、いかなる保証も一切ありません。
詳しくは、GNU General Public License を参照してください。
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/.
{ print $3 }
[vagrant@localhost awk]$ awk -f ex1.awk sales.dat
コマンドラインで、1行で表すこともできます。
awk ‘{print $3}’ sales.dat
行番号の表示
{
print NR ":" $0
}
パターン
NR < 5{
print NR ":" $0
}
NR > 10{
print NR ":" $0
}
FS
BEGIN{
print "--start --"
FS = "-"
}
{
print $1
}
NR < 5{
# print NR ":" $0
}
NR > 10{
# print NR ":" $0
}
END {
print "-- end --"
}
条件
(NR == 5) || (NR > 10){
print NR ":" $0
}
正規表現
$2 ~ /item-[23]/ {
print $0
}
printとprintfの違い
{
printf("%s %d\n", $1, $3)
}
表示を整理
{
printf("%-10s %5d\n", $1, $3)
}
変数
BEGIN{
sum = 0
}
{
sum = sum + $3
}
END{
print sum
}
組み込み関数
{
printf("%f, %d\n", rand(), int($3/3))
}