Here is the content of two files :

Judi # cat File1  
judi /export/home 76  
judi /usr 83  

judi # cat File2  
judi /export/home 79  
judi /usr 82  

If column 3 of File2 is greater that column 3 of File1, then print File2's lines

judi /export/home 79

  • do you mean for each line? can you complete your example in order to make your question clearer? thx – lese Nov 9 '15 at 16:02
  • Are the rows always in the same order? If they're not does the script need to find the corresponding row in the other file or should it just compare the same numbered row? – David King Nov 9 '15 at 16:02
  • the rows will not be in same order, The predefined value will be available in File1, the current status will be captured in File2, if COLUMN3 of File2 is greater than COLUMN3 of File1, then print File2's lines @David King – judi Nov 9 '15 at 16:08
awk 'NR==FNR{a[$1$2]=$3;next}$3>a[$1$2]&&a[$1$2]{print $0}' file1 file2

First file1 is read and array a filled with third column, indexed with 1st and 2nd column. Later on 3rd value of file2 is compared with a and if is larger then the whole line is printed.

for line in $(cat file1); do
  path=$(echo $line|cut -d' ' -f2)
  value1=$(echo $line|cut -d' ' -f3)
  value2=$(grep " $path " file2|cut -d' ' -f3)

  if [[ "$(echo \"$value2>$value1\"|bc)" == "1" ]]; then
    grep " $path " file2;
  • Thanks @jimmij, this one liner works for me awk 'NR==FNR{a[$1$2]=$3;next}$3>a[$1$2]&&a[$1$2]{print $0}' file1 file2 – judi Nov 9 '15 at 16:39

For the case when the rows are in the same order, there is a much cleaner solution using paste to combine the files before processing. The command paste file1 file2 will merge the corresponding lines of file1 and file2, like so:

$ cat file1
judi /export/home 76
judi /usr 83
$ cat file2
judi /export/home 79
judi /usr 82
$ paste file1 file2
judi /export/home 76    judi /export/home 79
judi /usr 83    judi /usr 82

You can then use this in a pipeline to awk like so:

$ paste file1 file2 | awk '$6 > $3 {print $4, $5, $6}'
judi /export/home 79

Of course, this won't work properly if the rows aren't in the same order (as in your case), but it does answer the title question: "Compare two files column values using awk".

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.