awk:在列中找到最小值和最大值 [英] awk: find minimum and maximum in column

查看:173
本文介绍了awk:在列中找到最小值和最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 awk 处理一个简单的.dat文件,该文件包含几行数据,每行有4列,并用一个空格分隔. 我想找到第一列的最小值和最大值.

I'm using awk to deal with a simple .dat file, which contains several lines of data and each line has 4 columns separated by a single space. I want to find the minimum and maximum of the first column.

数据文件如下:

9 30 8.58939 167.759
9 38 1.3709 164.318
10 30 6.69505 169.529
10 31 7.05698 169.425
11 30 6.03872 169.095
11 31 5.5398 167.902
12 30 3.66257 168.689
12 31 9.6747 167.049
4 30 10.7602 169.611
4 31 8.25869 169.637
5 30 7.08504 170.212
5 31 11.5508 168.409
6 31 5.57599 168.903
6 32 6.37579 168.283
7 30 11.8416 168.538
7 31 -2.70843 167.116
8 30 47.1137 126.085
8 31 4.73017 169.496

我使用的命令如下.

min=`awk 'BEGIN{a=1000}{if ($1<a) a=$1 fi} END{print a}' mydata.dat`
max=`awk 'BEGIN{a=   0}{if ($1>a) a=$1 fi} END{print a}' mydata.dat`

但是,输出为 min = 10 max = 9 .

(类似的命令可以向我返回第二列的正确的最小值和最大值.)

(The similar commands can return me the right minimum and maximum of the second column.)

有人可以告诉我我错了吗?谢谢!

Could someone tell me where I was wrong? Thank you!

推荐答案

Awk猜测类型.

字符串"10"小于字符串"4",因为字符"1"在"4"之前. 强制类型对话,使用零加法:

String "10" is less than string "4" because character "1" comes before "4". Force a type conversation, using addition of zero:

min=`awk 'BEGIN{a=1000}{if ($1<0+a) a=$1} END{print a}' mydata.dat`
max=`awk 'BEGIN{a=   0}{if ($1>0+a) a=$1} END{print a}' mydata.dat`

这篇关于awk:在列中找到最小值和最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆