user1703276
user1703276

Reputation: 363

How to replace multiple empty fields into zeroes using awk

I am using the following command to replace tab delimited empty fields with zeroes.

awk 'BEGIN { FS = OFS = "\t" } { for(i=1; i<=NF; i++) if($i ~ /^ *$/) $i = 0 }; 1'

How can I do the same, if I have the following input that is not tab delimited and have multiple empty fields ?

input

name              A1348138      A1086070      A1080879      A1070208      A821846       A1068905      A1101931
g1                5       8       1       2       1       3       1
g2                   1       3       2       1       1       2

desired output

name              A1348138      A1086070      A1080879      A1070208      A821846       A1068905      A1101931
g1                5       8       1       2       1       3       1
g2                   1       3       2       1       1       2       0

Upvotes: 0

Views: 171

Answers (1)

Ed Morton
Ed Morton

Reputation: 204731

I'd suggest using GNU awk for FIELDWIDTHS to solve the problem you appear to be asking about and also to convert your fixed-width input to tab-separated output (or something else sensible) while you're at it:

$ cat file
1   2   3
4       6

$ gawk -v FIELDWIDTHS='4 4 4' -v OFS='\t' '{for (i=1;i<=NF;i++) {gsub(/^[[:space:]]+|[[:space:]]+$/,"",$i); $i=($i==""?0:$i)}; print}' file
1   2   3
4   0   6

$ gawk -v FIELDWIDTHS='4 4 4' -v OFS=',' '{for (i=1;i<=NF;i++) {gsub(/^[[:space:]]+|[[:space:]]+$/,"",$i); $i=($i==""?0:$i)}; print}' file
1,2,3
4,0,6

$ gawk -v FIELDWIDTHS='4 4 4' -v OFS=',' '{for (i=1;i<=NF;i++) {gsub(/^[[:space:]]+|[[:space:]]+$/,"",$i); $i="\""($i==""?0:$i)"\""}; print}' file
"1","2","3"
"4","0","6"

Take your pick of the above.

Upvotes: 2

Related Questions