我有 4 列的空格分隔文件。我想利用 awk 找出每列的最大值。我的 awk 脚本应该在文件末尾输出该信息。
例如,如果我的文件是这样的:
Banana Oranges Lemons
Case_1 50 243 143
Case_2 45 443 103
Case_3 56 234 128
Case_4 64 164 183
Case_5 54 342 176
运行 awk 脚本后应该输出,
Banana Oranges Lemons
Case_1 50 243 143
Case_2 45 443 103
Case_3 56 234 128
Case_4 64 164 183
Case_5 54 342 176
Banana maximum happens at case 4: The complete line is
Case_4 64 164 183
Orange maximum happens at case 2: The complete line is
Case_2 45 443 103
有人可以帮我编写 awk 代码吗?
答案1
BEGIN {
col[0]=""
max[0]=""
casenum=0
text[0]=""
}
{ print $0 }
NR == 1 { split($0,col,FS); }
/Case_/ && NR > 1 {
casenum++
split($0,vals,FS)
text[casenum]=$0
for(i=1;i<=length(col);i++)
{
if(vals[i+1] > max[i])
{
max[i]=vals[i+1]
item[i]=casenum
}
}
}
END {
for(i=1;i<=length(col);i++)
{
printf "\n%s maximum happens at case %d: The complete line is\n",col[i],item[i]
print text[item[i]]
}
}
这会产生输出:
Banana Oranges Lemons
Case_1 50 243 143
Case_2 45 443 103
Case_3 56 234 128
Case_4 64 164 183
Case_5 54 342 176
Banana maximum happens at case 4: The complete line is
Case_4 64 164 183
Oranges maximum happens at case 2: The complete line is
Case_2 45 443 103
Lemons maximum happens at case 4: The complete line is
Case_4 64 164 183