简体   繁体   English

如何使用AWK打印最高编号的行?

[英]How to use AWK to print line with highest number?

I have a question. 我有个问题。 Assuming I dump a file and do a grep for foo and comes out the result like this: 假设我转储一个文件并为foo做一个grep,结果如下:

Foo-bar-120:'foo name 1'
Foo-bar-130:'foo name 2'
Foo-bar-1222:'foo name 3'

Etc. 等等。

All I want is trying to extract the foo name with largest number. 我想要的只是尝试提取最大数字的foo名称。 For instance in this case, largest number is 1222 and the result I expect is foo name 3 例如,在这种情况下,最大数字是1222,我期望的结果是foo name 3

Is there a easy way using awk and sed to achieve this? 有没有一种简单的方法使用awk和sed来实现这一目标? Rather than pull the number out line by line and loop through to find the largest number? 而不是逐行拉出数字并循环查找最大数字?

Code for : 代码:

awk -F[-:] '$3>a {a=$3; b=$4} END {print b}' file

$ cat file
Foo-bar-120:'foo name 1'
Foo-bar-130:'foo name 2'
Foo-bar-1222:'foo name 3'

$ awk -F[-:] '$3>a {a=$3; b=$4} END {print b}' file
'foo name 3'

假设行格式如“数字”前面的2个连字符所示:

cut -d- -f3- | sort -rn | sed '1{s/^[0-9]\+://; q}'

is this ok for you? 这对你好吗?

awk -F'[:-]' '{n=$(NF-1);if(n>m){v=$NF;m=n}}END{print v}'

with your data: 与您的数据:

kent$  echo "Foo-bar-120:’foo name 1’
Foo-bar-130:’foo name 2’
Foo-bar-1222:’foo name 3’"|awk -F'[:-]' '{n=$(NF-1);if(n>m){v=$NF;m=n}}END{print v}'
’foo name 3’

PS I like the Field separator [:-] PS我喜欢Field分隔符[:-]

Here's how I would do it. 这是我将如何做到这一点。 I just tested this in Cygwin. 我刚在Cygwin测试过这个。 Hopefully it works under Linux as well. 希望它也可以在Linux下运行。 Put this into a file, such as mycommand : 把它放到一个文件中,例如mycommand

#!/usr/bin/awk -f

BEGIN {
        FS="-";
        max = 0;
        maxString = "";
}

{
        num = $3 + 0; # convert string to int
        if (num > max) {
                max = num;
                split($3, arr, "'");
                maxString = arr[2];
        }
}

END {
        print maxString;
}

Then make the file executable ( chmod 755 mycommand ). 然后使文件可执行( chmod 755 mycommand )。 Now you can pipe whatever you want through it by typing, for example, cat somefile | ./mycommand 现在,您可以通过键入来管理您想要的任何内容,例如, cat somefile | ./mycommand cat somefile | ./mycommand . cat somefile | ./mycommand

$ awk '{gsub(/.*:.|.$/,"")} (NR==1)||($NF>max){max=$NF; val=$0} END{print val}' file
foo name 3

You don't need to use grep . 你不需要使用grep you can use awk directly on your file as: 您可以直接在文件中使用awk

awk -F"[-:]" '/Foo/ && $3>prev{val=$NF;prev=$3}END{print val}' file

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

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