Awk – to add a column after matching the remaining columns

awkperl

I have a file (file1.txt) with the contents as below.

8145216 3377090 1.5
1405541 53595498 1.53637

I need to generate all the possible combinations for the first 2 columns in the above file. I use a php program as discussed in this answer to generate all the combinations.

After finding out the combinations, I have my file as below.

3377090 8145216
1405541 8145216
1405541 3377090
53595498 8145216
53595498 3377090
53595498 1405541

In the above file, I need to append the 3rd column values from file1.txt and if the value is not present in the file1.txt I need to append 0 as the 3rd column. The final output that am trying to get is,

3377090 8145216 1.5
1405541 8145216 0
1405541 3377090 0
53595498 8145216 0
53595498 3377090 0
53595498 1405541 1.53637

Best Answer

awk 'NR==FNR{a[$1>=$2?$1SUBSEP$2:$2SUBSEP$1]=$3;next};
{k=$1>=$2?$1SUBSEP$2:$2SUBSEP$1; print $0, k in a?a[k]:0}' file1.txt file2.txt
3377090 8145216 1.5
1405541 8145216 0
1405541 3377090 0
53595498 8145216 0
53595498 3377090 0
53595498 1405541 1.53637
Related Question