How to use AWK to print the line with the highest number?

I have a question. Assuming I upload the file and do grep for foo and produce 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 name foo with the largest number. For example, in this case, the largest number is 1222, and the result I expect is foo name 3

Is there an easy way to use awk and sed to achieve this? Instead of pulling a number from a line and a line to find the largest number?

+4
source share
6 answers

This is how I do it. I just checked it in Cygwin. I hope it works on Linux as well. Put this in a file, for example 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 executable ( chmod 755 mycommand ). Now you can transfer whatever you want by entering, for example, cat somefile | ./mycommand cat somefile | ./mycommand .

+1
source

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'
+3
source

Assuming the line format is shown with two hyphens before the "number":

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

is it 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 [:-]

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

You do not need to use grep . you can use awk directly in your file as:

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

Source: https://habr.com/ru/post/1493308/


All Articles