sam_alloy
sam_alloy

Reputation: 57

How to update one file's column from another file's column in awk

I have two files, the first file:

1 AA
2 BB
3 CC
4 DD

and the second file

15 AA
17 BB
20 CC
25 FF

File 1 should be updated and the expected output should looks like this:

15 AA
17 BB
20 CC
4 DD

I have tried this script from another post but it didn't work

awk 'NR==FNR{a[$1]=$2;next}a[$1]{print $2,a[$1]}' file1 file2

Upvotes: 0

Views: 104

Answers (2)

Ed Morton
Ed Morton

Reputation: 203169

$ awk 'NR==FNR{a[$2]=$1; next} $2 in a{$1=a[$2]} 1' file2 file1
15 AA
17 BB
20 CC
4 DD

Upvotes: 1

dawg
dawg

Reputation: 103714

Here is an awk:

awk 'FNR==NR{f2[$2]=$0; next}
$2 in f2 {print f2[$2]; next}
1' file2 file1

Prints:

15 AA
17 BB
20 CC
4 DD

Upvotes: 0

Related Questions