简体   繁体   中英

Separating different sized blank spaces with awk and adding zeros to a column

I am having trouble in treating a table that is separated by different sized blank spaces and of different sized elements. Ideally I want all fields separated by a tab. I would also like to add a zero entry to any field elements that are blank. Not sure if awk FS/OFS is the most appropriate way here given that there are different sized blank spaces between fields.

If I do awk '{print $4}' I get a combo of column 4 and column 5 on the entries after 3rd row. So I feel I need a formal separator.

Current code (separator different sized blank spaces):

   1         0.98809     1.28484E-01 2.15265E-02 1.0559      1.1562      212.92      1.2248
   2         1.0222      5.81189E-01 1.24861E-04 1.0222      1.2548      216.26      1.8981
   3         1.1162      1.11291E-02             1.1256      1.2642      222.04      4.0946
   4         1.1922      2.0822                  1.1219      1.2826      216.16      4.1229

Expected code (separator tab, with zeros added in to fill blanks):

   1         0.98809     1.28484E-01 2.15265E-02 1.0559      1.1562      212.92      1.2248
   2         1.0222      5.81189E-01 1.24861E-04 1.0222      1.2548      216.26      1.8981
   3         1.1162      1.11291E-02 0.0         1.1256      1.2642      222.04      4.0946
   4         1.1922      2.0822      0.0         1.1219      1.2826      216.16      4.1229

A possible solution using GNU awk and its formatting using FIELDWIDTHS :

awk 'BEGIN{FIELDWIDTHS="13 12 12 12 12 12 12 12"; OFS="\t"} 
     {
        for(i=1;i<=NF;i++) 
          $i=($i+0?$i:sprintf("%-" length($i) "s","0.0"))
     }1' file

The script loops through all fields (not only the 4th one) to check if empty. If so, a 0.0 padded with spaces is assigned to the empty field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM