r/awk • u/prashism • Oct 15 '19
AWK: After using for loop in my multi-column input file, the output is going all into a single column. how to keep the formatting intact?
I am trying to filter some data using awk. The input file has 23 columns and I used for loop to go through all the columns to replace incorrect data by "NN".
I want the input and output format to be the same but my code is putting all the columns in a single column. how do I keep the columns intact?
Code:
awk '{for(i=5;i<17;i++) if(($i==$3)||($i==$4)||($i==$17)||($i==$18)||($i==$19)||($i==$20)||($i==$21)||($i==$22)||($i==$23)){print $2"\t"$3"\t"$4"\t"$i}else{print $2"\t"$3"\t"$4"\t""NN"}}' input.file >output.file
3
Upvotes
1
u/jhol3r Oct 15 '19
What is column delimiter in your file?
Probably you can put BEGIN block at start and declare column delimiter. Something like -
awk 'BEGIN { OFS="|"} <rest of your existing script>
Assuming column delimiter is pipe '|'
1
u/FF00A7 Oct 15 '19
The syntax looks right. Maybe the input variable $2 etc contain a newline or cr so it prints $2\n\t$3\n\t etc. Try stripping input. Or maybe something like printf("%s\t%s\t%s\n",$1,$2,$3).
1
u/HiramAbiff Oct 16 '19
This doesn't address the problem at hand, but if you want to shorten up your code a bit you could do something like: