newstudent
newstudent

Reputation: 444

FInd the minimum and print the corresponding column value

I have a dataset as given below:

35.7412  342  
35.7598  341  
35.7796  340  
35.8008  339   
35.8233  338   
35.8471  337   
35.8721  336   
35.8984  335  
35.9259  334   
35.9546  333   
35.9843  332 

Now, I need to find the minimum for several files and I do the following:

awk 'FNR==1 {
   if (min)
      print min
   min = ""
   fn = FILENAME
}
$1+0 == $1 && (min=="" || $1 < min) {
   min=$1
}
END {
   print min
}' *.txt

and obtain :

35.7412

But, I would like to print the corresponding value also, i.e.,

35.7412 342 

Any suggestions on how to print column $2 value ? Thanks

Upvotes: 0

Views: 87

Answers (3)

Ed Morton
Ed Morton

Reputation: 203324

awk '
    FNR == 1 {
        if (NR > 1) {
            print rec
        }
        min = $1
    }
    $1 <= min {
        min = $1
        rec = $0
    }
    END {
        print rec
    }
' *.txt

When doing min/max calculations, rather than initializing min/max to some arbitrary value, simply always initialize min/max to the first value read and then it'll work no matter what values your file contains, even if they're all negative values.

Upvotes: 4

RavinderSingh13
RavinderSingh13

Reputation: 133458

Could you please try following(written and tested in GNU awk).

awk '
FNR==1{
  delete val
  min=""
}
{
  min = (min<$1 ? (min ? min : $1) : $1)
  val[$1]=$0
}
ENDFILE{
  print val[min]
}
' *.txt

Explanation: Adding detailed explanation for above code.

awk '                                     ##Starting awk program from here.
FNR==1{                                   ##Checking condition if line is first line then do following.
  delete val                              ##Delete array named val here.
  min=""                                  ##Nullifying min variable value here.
}
{
  min = (min<$1 ? (min ? min : $1) : $1)  ##Creating variable min whose value we are checking is lesser than current $1 or not.
  val[$1]=$0
}
ENDFILE{                                  ##Using ENDFILE section for each Input_file here.
  print val[min]                          ##Printing array val value with variable min as index here.
}
' *.txt                                   ##Mentioning all .txt files here.

Upvotes: 3

Digvijay S
Digvijay S

Reputation: 2705

Using bash

for file in *txt;do sort -t" " -nr -k1 ${file} |  head -1; done;

OP's attempt

awk 'FNR==1 {
   if (min)
      print rec
   min = ""
   fn = FILENAME
}
$1+0 == $1 && (min=="" || $1 < min) {
   min=$1; rec=$0;
}
END {
   print rec
}' *.txt

Upvotes: 1

Related Questions