Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk script for finding smallest value from column

Tags:

awk

I am beginner in AWK, so please help me to learn it. I have a text file with name snd and it values are

1 0 141
1 2 223
1 3 250
1 4 280

I want to print the entire row when the third column value is minimu

like image 996
user1779084 Avatar asked Oct 27 '12 10:10

user1779084


People also ask

What is awk '{ print $4 }'?

'{print $4}' means print the fourth field (the fields being separated by : ).

What is awk '{ print $2 }'?

awk '{ print $2; }' prints the second field of each line. This field happens to be the process ID from the ps aux output.

What is awk '{ print $1 }'?

awk treats tab or whitespace for file separator by default. Awk actually uses some variables for each data field found. $0 for whole line. $1 for first field. $2 for second field.

What does $1 $2 indicate in awk file?

The awk variables $1 or $2 through $nn represent the fields of each record and should not be confused with shell variables that use the same style of names. Inside an awk script $1 refers to field 1 of a record; $2 to field 2 of a record.


1 Answers

This should do it:

awk 'NR == 1 {line = $0; min = $3}
     NR > 1 && $3 < min {line = $0; min = $3}
     END{print line}' file.txt

EDIT:

What this does is:

  • Remember the 1st line and its 3rd field.
  • For the other lines, if the 3rd field is smaller than the min found so far, remember the line and its 3rd field.
  • At the end of the script, print the line.

Note that the test NR > 1 can be skipped, as for the 1st line, $3 < min will be false. If you know that the 3rd column is always positive (not negative), you can also skip the NR == 1 ... test as min's value at the beginning of the script is zero.

EDIT2:

This is shorter:

awk 'NR == 1 || $3 < min {line = $0; min = $3}END{print line}' file.txt
like image 197
jfg956 Avatar answered Sep 21 '22 00:09

jfg956