Gawk 打印每列的最大值
我正在编写一个 awk 脚本,它接受文本文件中的一些输入列并打印出每列中的最大值
输入:
$cat numbers
10 20 30.3 40.5
20 30 45.7 66.1
40 75 107.2 55.6
50 20 30.3 40.5
60 30 45.O 66.1
70 1134.7 50 70
80 75 107.2 55.6
输出:
80 1134.7 107.2 70
脚本:
BEGIN {
val=0;
line=1;
}
{
if( $2 > $3 )
{
if( $2 > val )
{
val=$2;
line=$0;
}
}
else
{
if( $3 > val )
{
val=$3;
line=$0;
}
}
}
END{
print line
}
当前输出:
60 30 45.O 66.1
我做错了什么第一个 awk 脚本
=======解决方案======
END {
for (i = 0; ++i <= NF;)
printf "%s", (m[i] (i < NF ? FS : RS))
}
{
for (i = 0; ++i <= NF;)
$i > m[i] && m[i] = $i
}
感谢您的帮助
I am writing a awk script that takes some columns of input in a text file and print out the largest value in each column
Input:
$cat numbers
10 20 30.3 40.5
20 30 45.7 66.1
40 75 107.2 55.6
50 20 30.3 40.5
60 30 45.O 66.1
70 1134.7 50 70
80 75 107.2 55.6
Output:
80 1134.7 107.2 70
Script:
BEGIN {
val=0;
line=1;
}
{
if( $2 > $3 )
{
if( $2 > val )
{
val=$2;
line=$0;
}
}
else
{
if( $3 > val )
{
val=$3;
line=$0;
}
}
}
END{
print line
}
Current output:
60 30 45.O 66.1
What am I doing wrong first awk script
=======SOLUTION======
END {
for (i = 0; ++i <= NF;)
printf "%s", (m[i] (i < NF ? FS : RS))
}
{
for (i = 0; ++i <= NF;)
$i > m[i] && m[i] = $i
}
Thanks for the help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于您有四列,因此您至少需要四个变量,每一列一个变量(如果您愿意,也可以是一个数组)。而且您无需完全排队。独立处理每一列。
Since you have four columns, you'll need at least four variables, one for each column (or an array if you prefer). And you won't need to hold any line in its entirety. Treat each column independently.
您需要根据您的目的进行如下调整,这将找到特定列中的最大值(本例中为第二列)。
您采用的方法是 $2 > $3 似乎正在相互比较两列。
You need to adapt something like the following for your purposes which will find the maximum in a particular column (the second in this case).
The approach you are taking with $2 > $3 seems to be comparing two columns with each other.
您可以创建一个用户定义的函数,然后将各个列数组传递给它以检索最大值。像这样的东西 -
或
You can create one user defined function and then pass individual column arrays to it to retrieve the max value. Something like this -
or