Awk_ printing non-match in the array

Dear developpers,

I intend to compare the file1 to the file2 based on the values of column 1 in file1. However, the current code - that I modified from the forum- only print matches. I am wondering if there is a solution to have both matches and non matches being printed.
Many thanks in advance and sorry for the basic question

File1

abc    
ddd     
cnn     

File2

abc  zzz     
A	zzz    
A	zzz     
A	zzz 

Current code output :

awk -F"\t" 'FILENAME=="file1"{A[$1]=$1}
FILENAME=="file2" {if(A[$1]){print$0} else {????????"\t" "0"}}' file1 file2
abc zzz 
         0
         0
         0

The intended output ideally is similar to:

abc  zzz 
ddd   0
cnn   0

Hi, try:

awk 'NR==FNR{A[$1]=$2; next} {print $1, $1 in A? A[$1]:0}' file2 file1
1 Like

Thanks ! There is only a minor issue that is prints 'zero' in the front of the match as well :

abc 0
ddd 0
cnn 0

Ideally it should be

abc 
ddd 0
cnn 0

--- Post updated at 09:18 PM ---

Solved, Thank you!

Hello arsalane,

Good that you have solved the problem. I would like to request you to please do add that fix in this thread too, do that all users who are referring this thread in future could be benefitted too from that.

Keep up the learning and sharing on this great site Unix.com cheers.

Thanks,
R. Singh

Thanks! The code is absolutely fine. The issue was the corrupted input file format.

4 posts were split to a new topic: Identify rows in 2 text file that don't match. Here is my file structure:

This can be done using some simple scripting

~$ while read line; do found=$(grep -w $line test2.dat | wc -l); if [[ $found -ge 1 ]]; then echo $line; else echo "$line 0"; fi; done < test1.dat                    
abc
ddd 0
cnn 0

Can be shortened
grep ... | wc -l ==> grep -c ...