Writing to multiple files with awk

I have text files with multiple columns. I am using awk to write only the columns I want to an output file that I parse later.

awk 'BEGIN {FS="\t"}; {print $2,FS,$3,FS,$4} input_files*.txt >> output_file.txt

      

Is it possible to go one step further and redirect the output of my awk command to multiple files depending on the value of let say column $ 5? If column $ 5 = A, B, C and D, I get something like:

output_file_A.txt
output_file_B.txt
output_file_C.txt
output_file_D.txt

      

Thank.

Carlos

+3


source to share


2 answers


 awk 'BEGIN {FS="\t"}; {print $2,FS,$3,FS,$4 >> "output_file_"$5} input_files*.txt

      



The redirection internally awk

works exactly the same as the terminal.

+2


source


You can use this one awk

:



awk 'BEGIN {FS="\t"}; {fn="output_file_" $5 ".txt"} {print $2,FS,$3,FS,$4 > fn} input_files*.txt

      

+2


source







All Articles