Search code examples
awkprintingconditional-statementsdefaultkey-value

Using awk, conditionally print default value based on key,value not existing in second file


This is a variant on Using awk how do I combine data in two files and substitute values from the second file to the first file?

The reason this question is not the same as the one linked above is that this one handles a couple of additional cases.

data.txt contains some data:

A;1
B;2
C;3
A;4

keys.txt contains "key,value" pairs, however, the key,value pair for C is missing:

A;60
B;50
D;30

Desired output

A;1;60
B;2;50
C;3;1
A;4;60

For all "key,value" pairs missing, append default value of 1 to those rows. Should also be able to handle "key,value" pairs in keys.txt which doesn't have a corresponding key in data.txt (such as D;30 in this example).


Solution

  • awk to the rescue!

    compared to the related answer remove in filter and replace last field with a conditional.

    $ awk 'BEGIN   {FS=OFS=";"}
           NR==FNR {a[$1]=$2; next}
                   {print $0,($1 in a)?a[$1]:1}' file2 file1
    
    A;1;60
    B;2;50
    C;3;1
    A;4;60