CSVファイルで、特定の国の最大値を持つ最大の行を見つけます。

CSVファイルで、特定の国の最大値を持つ最大の行を見つけます。

次のエントリを含む.csvファイルがあります。

Location,Indicator,Period,First Tooltip
Afghanistan,Malaria incidence (per 1 000 population at risk),2018,29
Afghanistan,Malaria incidence (per 1 000 population at risk),2017,27
Afghanistan,Malaria incidence (per 1 000 population at risk),2016,26
Afghanistan,Malaria incidence (per 1 000 population at risk),2015,15
Afghanistan,Malaria incidence (per 1 000 population at risk),2002,104
Afghanistan,Malaria incidence (per 1 000 population at risk),2001,92
Afghanistan,Malaria incidence (per 1 000 population at risk),2000,96
Algeria,Malaria incidence (per 1 000 population at risk),2018,0
Algeria,Malaria incidence (per 1 000 population at risk),2017,0
Algeria,Malaria incidence (per 1 000 population at risk),2013,0


シェルスクリプトから返された引数で国名を指定し、次を出力するシェルスクリプトを作成したいと思います。

./scrip.sh Afghanistan  
For Afghanistan, the year is 2002; the rate is 104 per 1,000  

デフォルトでは、その国の最大ツールヒントを含む行を選択して解析し、
上記の出力を生成します。

私の考え:
シェルスクリプトを使用してこれを行う方法がわかりません。
ここには2つの部分があります。最初の部分は、最大値を選択して
行を分割し、値を見つけて印刷することです。
進行方法のヒントやアイデア

ベストアンサー1

シェル+awk:

#!/usr/bin/env sh

country="$1"

if [ -z "$country" ]
then
    printf "Country not specified\n" >&2
    exit 1
fi


awk -v FS=, -v country="$country" '
    BEGIN { tooltip = 0; found = 0 }
    $1 == country { if ($NF > tooltip) {found = 1; tooltip = $NF; year = $(NF - 1)} }
    END {if (!found) {print "No entry for the specified country"; exit 1} print "For " country " the year is " year "; the rate is " tooltip " per 1,000"}' file.csv

ファイル名を指定していないのでfile.csv

$ ./script.sh Afghanistan
For Afghanistan the year is 2002; the rate is 104 per 1,000
$ ./script.sh abc
No entry for the specified country

おすすめ記事