I'm trying to get AWK filling up following text file for "empty" columns".

Basic idea of finding longest line with AWK NF and checking which line has no value on that column. Then adding x times N/A for each empty column.

This example is input space separated, but of course it can be changed easily to any character separated file.

Input can be as:

aaa bbb ccc ddd
aaa bbb ccc
hhh ppp uuu
www yyy hhh
hhh 111 333 yyy ooo hyy uuuioooy 

And output where amount of max columns in file is calculated and N/A added to columns that empty.

aaa bbb ccc ddd N/A N/A N/A
aaa N/A N/A N/A N/A N/A N/A
aaa bbb ccc N/A N/A N/A N/A
hhh ppp uuu N/A N/A N/A N/A 
www yyy hhh N/A N/A N/A N/A 
hhh 111 333 yyy ooo hyy uuuioooy 
  • I messed up output, now edited.
    – tiny
    Aug 31 '12 at 8:16

The easiest way is to do it in two steps, first find the widest line:

max=$(awk 'max < NF { max = NF } END { print max }' infile)

Then use that as input when filling out the other columns:

awk -v max=$max '{ for(i=NF+1; i<=max; i++) $i = "N/A"; print }' infile
  • I figured out as well that best way it in two steps. Helps me to understand this better as well. Thanks.
    – tiny
    Aug 31 '12 at 8:37
  • 2
    You need an END{print max} on that first one.
    – Kevin
    Aug 31 '12 at 21:44
  • @kevin: must have missed it in the copy pasting, thanks.
    – Thor
    Aug 31 '12 at 23:06
awk 'FNR==NR{if(m<NF)m=NF;next}{for(i=NF;i<m;i++)$(i+1)="N/A"}1' tiny.txt tiny.txt

Note the input file name specified twice.

  • Very cool usage of AWK where to input files are used. Thanks!
    – tiny
    Aug 31 '12 at 8:38
  • I came to realize your AWK snipped leaves missing one column from the end.
    – tiny
    Aug 31 '12 at 13:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.