judi
judi

Reputation: 99

compare two files column values

File1:

judi /var 80  
judi / 76  
judi /opt 85 

File2:

judi /var 80  
judi / 80  
judi /opt 86 

In the File2 "/" value is (80) high than File1 (76)
In the File2 "/opt" value is (86) high than File1 (85)

I need to get the output of only highest values

judi / 80  
judi /opt 86 

Upvotes: 0

Views: 70

Answers (1)

John1024
John1024

Reputation: 113834

$ paste file1 file2 | awk '$6>$3{print $4,$5,$6} $6<$3{print $1,$2,$3}'
judi / 80
judi /opt 86

How it works

  • paste file1 file2

    This merges the lines together like:

    $ paste file1 file2
    judi /var 80    judi /var 80
    judi / 76       judi / 80
    judi /opt 85    judi /opt 86
    
  • $6>$3{print $4,$5,$6}

    If the sixth field is larger than the third (meaning the value in file2 is larger than the value in file1), then print the values from file2.

  • $6<$3{print $1,$2,$3}

    Alternatively, if the third field is larger than the sixth (meaning the value in file1 is larger than the value in file2), then print the values from file1.

Handling an alternate format

Suppose that each file can contain any number of space-separated fields while the number that we want to compare will always be the last field. In that case:

$ awk -v f=file2 '{a=$0; n=$NF; getline <f} n>$NF{print a} n<$NF' file1
judi / 80
judi /opt 86

This reads from file1 and saves the whole line as variable a and the number in the last field as variable n. It then, using getline <f, reads from file2 which puts file2's whole line in variable $0 and last number in variable $NF. We then make the comparisons and print out the desired line.

Upvotes: 3

Related Questions