Why does my field separator get messed up when I substitute a value using awk?

Viewed 137

I'm quite new to awk so please apologise if this is a trivial question but I did not find a similar question or an answer that would fix my problem.

I want to do the following: I have a tab separated text file consisting of five columns like this:

Location    Indices gene    coordinates_1   coordinates_2
190..255    "190, 255"  thrL    "232, 237"  NA
337..2799   "337, 2799" thrA    "2094, 2102"    NA
2801..3733  "2801, 3733"    thrB    NA  2855
3734..5020  "3734, 5020"    thrC    NA  NA

Now I want to replace all "NA" values in the 4th column (coordinates_1) with 0 and save the file. In order to do this I wrote the following command:

awk '
BEGIN { FS = "\t" }
{
if ($4 == "NA")
    $4 = 0;
    print $0;
}' original_data.txt > NAs_to_zero.txt

My desired output should look like this:

Location    Indices gene    coordinates_1   coordinates_2
190..255    "190, 255"  thrL    "232, 237"  NA
337..2799   "337, 2799" thrA    "2094, 2102"    NA
2801..3733  "2801, 3733"    thrB    0   2855
3734..5020  "3734, 5020"    thrC    0   NA

However what now happens is that in each line where an NA was replaced with zero, the fields are no longer separated by tabs and therefore do not correspond to the original file.

Location    Indices gene    coordinates_1   coordinates_2
190..255    "190, 255"  thrL    "232, 237"  NA
337..2799   "337, 2799" thrA    "2094, 2102"    NA
2801..3733 "2801, 3733" thrB 0 2855
3734..5020 "3734, 5020" thrC 0 NA

Do I have to reassign a new separator somewhere in the command or how can I achieve that the fields in the file where the NAs were replaced by zero are still tab separated?

1 Answers

Yes, in awk there are separate variables to control input and output field separators. Default value for both is space character. The contents of $0 is rebuilt if any field is changed with the current value of OFS, which is why you saw the change to spaces only for the lines matching the given condition.

Also, you could simplify the code as (see https://backreference.org/2010/02/10/idiomatic-awk/)

awk 'BEGIN{FS=OFS="\t"} $4=="NA"{$4=0} 1'
Related