huang cheng
huang cheng

Reputation: 393

Bash-shell after matching one file from another file, print out both match content and not match content at one time

cat fiel1.txt
cheng 600
huang 500
pan 400
yin 300

cat file2.txt
600 a
300 c

After I execute

awk 'NR==FNR{a[$1]=$2;next}($2 in a){print $1,$2,a[$2]}' f2.txt f1.txt

The result as below:

cheng 600 a
yin 300 c

and I also want to print the column that not in array a . like below:

cheng 600 a
huang 500
pan 400
yin 300 c

How can I get the result. I try command like below:

awk 'NR==FNR{a[$1]=$2;next}($2 in a){print $1,$2,a[$2]}($2 not in a){print $1,$2,a[$2]}' f2.txt f1.txt

But it was failed.

Upvotes: 1

Views: 29

Answers (1)

John1024
John1024

Reputation: 113994

$ awk 'NR==FNR{a[$1]=$2;next} {if($2 in a)print $1,$2,a[$2]; else print $1,$2}' f2.txt f1.txt
cheng 600 a
huang 500
pan 400
yin 300 c

Discussion

You had:

($2 in a){print $1,$2,a[$2]}

This prints only if $2 is in a. We replaced that with:

if($2 in a)print $1,$2,a[$2]; else print $1,$2

This prints $1,$2,a[$2] is $2 is in a. Otherwise, it just prints $1,$2.

Simpler version

If you mind some extraneous trailing blanks, we can use the still simpler:

$ awk 'NR==FNR{a[$1]=$2;next} {print $1,$2,a[$2]}' f2.txt f1.txt
cheng 600 a
huang 500 
pan 400 
yin 300 c

Upvotes: 1

Related Questions