LoginSignup
1
1

More than 5 years have passed since last update.

awkで平均・カウントの集計

Last updated at Posted at 2016-08-01

awkを使えば平均やカウントを簡単に集計できる。
例えば、

sample1.txt
10 10
15  5
 3 12

というデータがあったときに、行の合計値を出すには、

sample1.awk
$cat sample1.txt | awk '{print $1+$2}'
20
20
15

とすればOK。行の合計値が20以上の行だけを抽出するには、

sample2.awk
cat sample1.txt | awk '{if($1+$2>=20) print $0}'
10 10
15  5

とすればOK。次のようにすれば、行の中での比率を算出することも可能。

sample3.awk
cat sample1.txt | awk '{print $1/($1+$2) " " $2/($1+$2)}'
0.5 0.5
0.8 0.2
0.2 0.8

1列目の比率が0.8以上の行だけを抽出するには、

sample4.awk
cat sample1.txt | awk '{if($1/($1+$2) >= 0.8) print $0}'
20  5

とすればOK。さらに、sortと組み合わせれば、

sample5.awk
cat sample1.txt | awk '{print $0" "$1/($1+$2)}' | sort -k3 -nr
20  5 0.8
10 10 0.5
 3 12 0.2

のように1行目の比率でソートすることも可能。

1
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
1
1