-3

I have many files like these:

file1:

 408.60 0.0847 
 370.03 0.1571 
 307.49 0.1492 
 297.12 0.0708 
 274.36 0.1989 
 251.27 0.1640 

file2:

 391.06 0.0589 
 368.55 0.2293 
 313.87 0.0369 
 299.94 0.1432 
 288.61 0.2125 
 252.57 0.1238 

file3:

 395.74 0.2439 
 372.76 0.0658 
 323.80 0.0026 
 287.41 0.3337 
 268.44 0.0860 
 259.44 0.0680 

I want to select specific lines of each input file based on a selection criteria. The selection criteria is:

a) the first column must be a number more than 290.00

b) the second column must be the highest number

c) print the line

The output should be like this:

370.03 0.1571
368.55 0.2293
395.74 0.2439
0

Direct solution

for file in file{1..3}; do
    sort -rk2 "$file" | awk '$1 > 290{print;exit}'
done

Or without awk

for file in file{1..3}; do
    while read field1 field2 ; do
        [ "field1" -gt 290 ] && { echo $field1 $field2; break; }
    done <(sort -rk2 "$file")
done

Or awk alone

awk '
    FNR == 1 || $1 > 290 && max < $2 {
        max = $2
        if (FNR == 1 && max) {
            print line
            if ($1 <= 290)
                max = -1     }
        line= $0                     }
    END {
        print line }
    ' file{1..3}
0
for f in file1 file2 file ; do cat $f | awk '{printf("%s %s\n",$2,$1)}' | sort -n | tail -n 1 | awk '{printf("%s %s\n",$1,$2)}' ; done
  • Instead of just writing some code without explanation, why not show what you are specifically doing in your code block and how it solves the issue. Also note that cat and tail are unnecessary since you are already using awk. – HalosGhost Jul 14 '16 at 18:20
0

Here's one way to do it, if you have GNU awk, which works by using the second field as an array index and using asorti to sort on that index at the end of each file

gawk '
  BEGINFILE{delete a}
  $1+0 > 290 {a[$2]=$0; next;}
  ENDFILE{n = asorti(a,b); print a[b[n]]}
' file{1..3}
 370.03 0.1571 
 368.55 0.2293 
 395.74 0.2439

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.