Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 
share|improve this question
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 out 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
share|improve this answer
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
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.

share|improve this answer
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
Indeed. Corrected. Thanks. – manatwork Aug 31 '12 at 13:33

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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