Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use AWK to print line with highest number?

Tags:

linux

sed

awk

I have a question. Assuming I dump a file and do a grep for foo and comes out the result like this:

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. For instance in this case, largest number is 1222 and the result I expect is foo name 3

Is there a easy way using awk and sed to achieve this? Rather than pull the number out line by line and loop through to find the largest number?

like image 303
Petre Lamar Avatar asked Mar 24 '23 01:03

Petre Lamar


1 Answers

Code for awk:

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'
like image 83
captcha Avatar answered Apr 01 '23 22:04

captcha