我有一個問題,采用以下設定的昏迷分隔 CSV 我想在 bash 中運行一個腳本,該腳本對來自特定城市的第 7、8、9 列的所有值求和,并顯示具有最大值的行,因此原始資料集:
Row,name,city,age,height,weight,good rates,bad rates,medium rates
1,john,New York,25,186,98,10,5,11
2,mike,New York,21,175,87,19,6,21
3,Sandy,Boston,38,185,88,0,5,6
4,Sam,Chicago,34,167,76,7,0,2
5,Andy,Boston,31,177,85,19,0,1
6,Karl,New York,33,189,98,9,2,1
7,Steve,Chicago,45,176,88,10,3,0
the desire output will be
Row,name,city,age,height,weight,good rates,bad rates,medium rates,max rates by city
2,mike,New York,21,175,87,19,6,21,46
5,Andy,Boston,31,177,85,19,0,1,20
7,Steve,Chicago,45,176,88,10,3,0,13
我正在嘗試這個;但它只給了我最高的費率數字,所以 46 但我需要它按城市顯示所有行,任何想法如何繼續?
awk 'BEGIN {FS=OFS=","}{sum = 0; for (i=7; i<=9;i ) sum = $i} NR ==1 || sum >max {max = sum}
uj5u.com熱心網友回復:
你可以使用這個 awk:
awk '
BEGIN {FS=OFS=","}
NR==1 {
print $0, "max rates by city"
next
}
{
s = $7 $8 $9
if (s > max[$3]) {
max[$3] = s
rec[$3] = $0
}
}
END {
for (i in max)
print rec[i], max[i]
}' file
Row,name,city,age,height,weight,good rates,bad rates,medium rates,max rates by city
7,Steve,Chicago,45,176,88,10,3,0,13
2,mike,New York,21,175,87,19,6,21,46
5,Andy,Boston,31,177,85,19,0,1,20
或獲取表格輸出:
awk 'BEGIN {FS=OFS=","} NR==1{print $0, "max rates by city"; next} {s=$7 $8 $9; if (s > max[$3]) {max[$3] = s; rec[$3] = $0}} END {for (i in max) print rec[i], max[i]}' file | column -s, -t
Row name city age height weight good rates bad rates medium rates max rates by city
7 Steve Chicago 45 176 88 10 3 0 13
2 mike New York 21 175 87 19 6 21 46
5 Andy Boston 31 177 85 19 0 1 20
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/399215.html
上一篇:嵌套的bash回圈只執行一次
下一篇:如何獲取根元素包含特定字符
