简体   繁体   English

使用 AWK 比较同一列中的值

[英]Using AWK to compare values in the same column

I'm using AWK and I've been trying to compare the previous value in a column with the next one until it finds the highest but I haven't been able to.我正在使用 AWK,我一直在尝试将列中的前一个值与下一个值进行比较,直到找到最高值,但我无法做到。

awk '$6 >= $6 {print $6}'

With the above, it returns me every single value有了上面,它返回给我每一个值

For example:例如:

money:
49
90
30
900

I would like it to return 900我希望它返回 900

$ awk '(NR>1) && ((NR==2) || ($1>max)){max=$1} END{if (max != "") print max}' file
900

The above is based on your posted example (including the money: header line) but would also work even if all input values were 0 or negative or the input file was empty.以上基于您发布的示例(包括money:标题行),但即使所有输入值为0或负数或输入文件为空,也可以使用。 Change $1 to $6 if the real field number you're interested in is 6.如果您感兴趣的真实字段数是 6,则将$1更改为$6 6。

Also consider:还要考虑:

$ tail -n +2 file | cut -f1 | sort -rn | head -1
900

and change -f1 to -f6 .并将-f1更改为-f6

Set separator chars in awk with -F'<char>' and cut with -d'<char>' if necessary.使用-F'<char>'在 awk 中设置分隔符,必要时使用-d'<char>'剪切。

像这样:

awk 'int($6) && $6 > n{n=$6}END{print n}' file

Assuming the columns are separated by the default (white-space) separator, the following awk line checks the 6th value in each data row to see if it is greater than any previously seen values ( current set in a BEGIN block to zero, gets updated each time a greater 6th value is encountered).假设列由默认(空白)分隔符分隔,以下 awk 行检查每个数据行中的第 6 个值,以查看它是否大于任何先前看到的值( currentBEGIN块中设置为零,得到更新每次遇到更大的第 6 个值时)。 The END block prints the final value held in current (which is the greatest value for the 6th field)" END块打印current保存的最终值(这是第 6 个字段的最大值)"

awk 'BEGIN {current=0} NR>1{if ($6>current) current=$6} END {print current}' dataFile.txt

For .csv data, the file separator can be defined as a comma with FS="," in the BEGIN block:对于.csv数据,文件分隔符可以在BEGIN块中定义为带有FS=","的逗号:

awk 'BEGIN {FS=","; current=0} NR>1{if ($6>current) current=$6} END {print current}' dataFile.csv
$ awk 'NR==2  {max=$6} 
       $6>max {max=$6} 
       END    {print max}' file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM