Comparing two files with out sorting AWK

Viewed 63

I have two files like this:

Animal Food
cat    fish
Dog    meet
cow    grass

second file:

Animal Food Price
cat    fish  45
Dog    meet  47
Got    grass 74

I just want to compare these two files based on the first and second column as like this:

Animal Food Price
cat    fish  45
Dog    meet  47

Usually, I will perform this with the JOIN function but in this case, sorting is not possible. I need results exactly the same order as on file 1 Then I tried with AWK as like this:

awk 'NR==FNR {$1 = $2; next} {print}' file1 file2

But it is producing some duplicate results and different order.

2 Answers

You may use:

awk '{k = $1 FS $2} NR == FNR {map[k]=$3; next} k in map{print $0, map[k]}' f2 f1
Animal Food Price
cat    fish 45
Dog    meet 47

You actually can do it with join and sorting is possible, you just have to decorate the input to join with the original line numbers so you can re-sort on those line numbers again in the output:

$ cat tst.sh
#!/usr/bin/env bash

encode() {
    awk '{print $1 SUBSEP $2, NR, $0}' "${@:--}" |
    sort
}

decode() {
    sort -k2,2n "${@:--}" |
    awk '{sub("^([^[:space:]]+[[:space:]]+){"NF/2+1"}","")} 1'
}

join <(encode "$1") <(encode "$2") | decode

.

$ ./tst.sh file1 file2
Animal Food Price
cat fish 45
Dog meet 47

In real life I'd just go with what @anubhava has of course, unless I ran into memory issues or similar, the above is just for the sake of demo-ing an alternative.

Related