Dorukhan Arslan
Dorukhan Arslan

Reputation: 2754

Reading from a file and writing to another using Awk

There are two tab delimiter text files. My aim is to change File 1 so that corresponding values in the 2nd column of File 2 will be substituted with zeros in File 1.

To visualize,

File 1:

AA 0
BB 0
CC 0
DD 0
EE 0

File 2:

AA 256
DD 142
EE 26

File 1 - Output:

AA 256
BB 0
CC 0
DD 142
EE 26

I wrote below but as you can see I give the value of 1st row of File 2 by hand. I want to achieve this task automatically. What should I do?

awk -F'\t' 'BEGIN {OFS=FS} {if($1 == "AA") $2="256";print}' test > test.tmp && mv test.tmp test

Thank you in advance.

Upvotes: 0

Views: 701

Answers (1)

Ed Morton
Ed Morton

Reputation: 203532

awk 'BEGIN {FS=OFS="\t"} NR==FNR{a[$1]=$2; next} {print $1, a[$1]+0}' file2 file1

Upvotes: 4

Related Questions