Matching and replacing variables in columns using AWK

Viewed 84

I am matching and replacing values in file2.txt using values in file1.txt. The values that don't match need to be replaced by NA. I have tried to write a small AWK code below, but doesn't give output as required. Any suggestion or help is welcomed.

awk 'FNR==NR 
{ a[$1]=$2;next}
{
for (i=1;i<=NF;i++) {
$i = ($i in a) ? a[$i] : "NA"
}
}1' file1.txt file2.txt

Instead I get output as below:

NAk
NAt1
NAp1
...

Sample files: file1.txt

EN01    Car
EN28    Bus
EN37    Scooter
EN49    Van

file2.txt

EN01    EN28
EN28    EN37
ENXX    EN49
EN01    EN28

output (I require)

Car   Bus
Bus   Scooter
NA    Van
Car   Bus

_

1 Answers

Perhaps

awk '
    NR == FNR {vehicle[$1] = $2; next}
    function get(id) { return id in vehicle ? vehicle[id] : "NA" }
    {print get($1), get($2)}
' file1.txt file2.txt | column -t

The error in your code is the newline after FNR==NR: the condition must be on the same line as the action block. See the awk tag info page.

Related