AWK for filling up rest of the columns with &nbsp in file

awktext processing

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 
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 

Best Answer

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
Related Question