fill in last column of data

Hello,

I am fairly new to awk, and I have the following problem.

My file has missing data in the last column, and the program I am pre-processing this file for cannot interpret correctly shortened rows (it just wraps the data around).

Is there a way to force awk to create the same number of columns for each row (based on the number of headers in the first row), even if the column is blank? Or, alternatively, how can I fill in missing data in the last column with "N/A" or something like that.

Thank you for your help.

Try using printf instead of print...

1 Like

Thanks. Is it possible to make this work without knowing how many columns the file has? (i.e. can I put a for loop inside a printf statement?)

the below code checks for three fileds, and if it is not there, then fill with "NA"

 
$ cat test.txt 
one two three
one two
one 
one two three
$ nawk '{if(NF<3){for(i=1;i<=3;i++){if($i!~/./){printf("NA ")}else{printf("%s ",$i)}if(i==3){printf("\n")}}}else{print}}' test.txt
one two three
NA NA NA 
one two NA 
NA NA NA 
one NA NA 
NA NA NA 
one two three

Can you give a sample input and sample output you are expecting please???

Thanks for your help. Here is what I ended up doing:

{
 i = 1
 if (NR == 1) {
  numfields=NF;
  for (i=1; i<=(numfields-1); i++) {
   printf "%s\t", $(i) ;
  }
  printf "%s\n", $(numfields) ;
 } else if (NR < 10) {
  for (i=1; i<=(numfields-1); i++) {
   printf "%s\t", $(i) ;
  }
  printf "%s\n", $(numfields) ;
 } 
}

Little modify in kamaraj's code ..

$ a=$(awk 'NR==1{print NF}' infile)
$ awk -v val="$a" '{if(NF<val){for(i=1;i<=val;i++){if($i!~/./){printf("NA ")}else{printf("%s ",$i)}if(i==val){printf("\n")}}}else{print}}' infile
one two three
one two NA
one NA NA
one two three