Redson
Redson

Reputation: 2140

How do I check if a field is empty or null in a text file using awk and bash

I have two text files and I want to compare their correspondent values according to their rows and columns. Each value (field) in the text file is separated by tabs.

Here are the files:

file1.txt

Name  Col1  Col2  Col3  
-----------------------
row1  1     4     7        
row2  2     5     8         
row3  3     6     9 

file2.txt

Name  Col1  Col2  Col3  
-----------------------
row2  1     4     11        
row1  2     5     12
row3  3          9 

Here is the code I have so far:

awk '
FNR < 2 {next}                       
FNR == NR {           
    for (i = 2; i <= NF; i++) {
        a[i,$1] = $i;      
    }              
    next;       
}

# only compare if a row in file2 exists in file1
($1 in b) {                                          
    for (i = 2; i <= NF; i++) 
    {
        if (a[i,$1] == $i) 
        {
             print "EQUAL"       
        }
        else if ( //condition that checks if value is null// )
        {
             print "NULL" 
        }
        else
        {
             print "NOT EQUAL"
        }
    }
}' file1.txt file2.txt

I am having difficulties with checking if there is a null value (row3 and col2 in file2.txt) in file2.txt. I don't even get an output for that null value. So far I tried if ($i == "") and it is still not giving me any output. Any suggestions? Thanks. (I'm using gnu awk in a bash script)

Let me know if further explanation is required.

Upvotes: 1

Views: 6184

Answers (1)

Ed Morton
Ed Morton

Reputation: 203625

Just set the FS to tab:

awk -F'\t' '....'

Upvotes: 2

Related Questions