Modify blocks of text by printing missing columns

Hi Experts,

I have a problem where I want to print missing columns (3,4) within a block of text. Each block is separated by "###". Some rows have missing column 3 and 4 which should be same as the previous value in column 3 and 4. The file is space delimited.
For example:

INPUT

###
625204690_cc   100.00%   568928245_mm   100.00%
625204692_cc   100.00%   568928247_mm   100.00%
625204688_cc   98.76%
625205698_cc   95.76%
625204600_cc   100.00%   568928555_mm   100.00%
###
625287481_cc   100.00%   568925788_mm   100.00%
625181641_cc   75.61%   568925790_mm   99.50%
124487133_cc   70.91%

OUTPUT

###
625204690_cc   100.00%   568928245_mm   100.00%
625204692_cc   100.00%   568928247_mm   100.00%
625204688_cc   98.76%   568928247_mm   100.00%                            
625205698_cc   95.76%   568928247_mm   100.00%
625204600_cc   100.00%   568928555_mm   100.00%
###
625287481_cc   100.00%   568925788_mm   100.00%
625181641_cc   75.61%   568925790_mm   99.50%
124487133_cc   70.91%   568925790_mm   99.50%

I'll be really thankful for your help.

awk '/#/ { for(N=2; N<=4; N++) delete A[N] ; print ; next }
        { for(N=2; N<=4; N++)
           {
                if($N) { A[N]=$N }
                else if(N in A) $N=A[N]
           }
} 1' infile > outfile
1 Like

Thanks a lot Corona! It works perfect :). It would be great if you can briefly explain the code.

Thanks again for your help.

Far from being an awk expert, but I managed to patch following together:

awk '$0 ~ /^#/ {print}
    NF==4 {f3=$3;f4=$4;print $0}
    NF==2 {print $0"   "f3"   "f4}' input

Explanation:
$0 ~ /^#/ {print}
If line starts with hash "#", print it unmodified

NF==4 {f3=$3;f4=$4;print $0}
If line has four fields, assign value of field 3 to variable f3, assign value of field 4 to variable f4, print the whole line unmodified

NF==2 {print $0" "f3" "f4}
If line has two fields, print the whole line unmodified, append values stored in f3 and f4

Hope this helps.

1 Like
1 Like

Thanks a lot! Corona and Junior-helper for explanation. :slight_smile: