1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[AWK] 最大値・最小値のグループ集計

Last updated at Posted at 2019-11-27

やりたいこと

例えば下記のようなデータがあった時に、1列目をグループとして、2列目の最小値と3列目の最大値を抽出します。

もともとのデータ
cat input.txt
hoge 10 10
hoge 20 30
hoge 30 20
fuga 1 5
fuga 10 10
集計後
cat output.txt
hoge 10 30
fuga 1 10

AWKのコード

# input.txtの生成
cat << EOF > input.txt
hoge 10 10
hoge 20 30
hoge 30 20
fuga 1 5
fuga 10 10
EOF

# 集計コード
cat input.txt |
awk '{if(min[$1] == "") min[$1]="inf"
if(min[$1]>$2) min[$1]=$2
if(max[$1]<$3) max[$1]=$3}
END{for(key in min) print key, min[key], max[key]}' \
> output.txt

工夫したところ

最小値を求めるときにはawkがとり得る最大値infを代入します。
そのためにif(min[$1]) == 0min[$1]で、min[$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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?