1
votes

I need and awk script that compare the first column of two files tab-delimited and each time there is a match I need to print the second file else I need all the lines of the first file

file1.txt

denovo0  bacteria   0.99  
denovo1  bacteria   0.98  
denovo2  bacteria;Firmicutes;clostridium    0.99  
denovo3  bacteria;Firmicutes;bacillus   0.98  

file2.txt

denovo0  bacteria;Gammaproteobacteria;pseudomonas   0.99  
denovo1  bacteria;Alphaproteobacteria;Rhizobium     0.98

desired_output.txt

denovo0  bacteria;Gammaproteobacteria;pseudomonas  0.99  
denovo1  bacteria;Alphaproteobacteria;Rhizobium  0.98  
denovo2  bacteria;Firmicutes;clostridium    0.99  
denovo3  bacteria;Firmicutes;bacillus   0.98  
2
code tags are for better understanding of question/answers please add them again to have a better look to your post, also please specify more clearly about your problem with examples.RavinderSingh13

2 Answers

1
votes
awk 'NR==FNR{a[$1]=$1;b[$1]=$0;next} $1==a[$1]{print $0 ;delete b[$1]}END{for (i in b ) print b[i]}'  file1 file2

Explanation

NR==FNR{a[$1]=$1;b[$1]=$0;next} : reads file1 and assigns array a with first column and b with the line as value.

$1==a[$1]{print $0 ;delete b[$1]} : checks if value in a matches with 1st column of file2 if yes then print the line of file2 and deleted that line from array b.

END{for (i in b ) print b[i]} : prints the remaining items in array b i.e remaining lines of file1

1
votes

This awk should work for you:

awk -v OFS='\t' 'NR==FNR{a[$1]=$2; next} $1 in a{$2=a[$1]} 1' file2 file1

denovo0 |bacteria;Gammaproteobacteria;pseudomonas| 0.99
denovo1 |bacteria;Alphaproteobacteria;Rhizobium| 0.98
denovo2 |bacteria;Firmicutes;clostridium|   0.99
denovo3 |bacteria;Firmicutes;bacillus|  0.98

If you want a tabular output then pipe it to column -t

awk -v OFS='\t' 'NR==FNR{a[$1]=$2; next} $1 in a{$2=a[$1]} 1' file2 file1 | column -t

denovo0  |bacteria;Gammaproteobacteria;pseudomonas|  0.99
denovo1  |bacteria;Alphaproteobacteria;Rhizobium|    0.98
denovo2  |bacteria;Firmicutes;clostridium|           0.99
denovo3  |bacteria;Firmicutes;bacillus|              0.98