Try:
$ awk -F, -v OFS=, 'FNR==NR{a[$1]=$2; next} NF==1{$2=a[$1]} 1' source.txt test.txt
A,1000
C,2500
D,5000
B,3000
E,4000
How it works:
-F, -v OFS=,
This sets the input and output field separator to a comma.
FNR==NR{a[$1]=$2; next}
When reading the first file, source.txt
, save the value of the second field, $2
, in associative array a
under the key of the first field, $1
. Then skip the rest of the commands and jump to start over on the next
line.
NF==1{$2=a[$1]}
If the current line has only one field, assign the second field to the value in associative array a
.
1
This is short-hand for print the line.
Making permanent changes to the file
With any version of awk, we can make a permanent update to file test.txt
with (recommended):
awk -F, -v OFS=, 'FNR==NR{a[$1]=$2; next} NF==1{$2=a[$1]} 1' source.txt test.txt >temp && mv temp test.txt
Alternatively, if one has a recent version of GNU awk
(sometimes called gawk
):
awk -i inplace -F, -v OFS=, 'FNR==NR{a[$1]=$2; print; next} NF==1{$2=a[$1]} 1' source.txt test.txt
source.txt
? – finswimmer May 15 '19 at 04:32