The results from print and printf functions can be redirected to a shell command or a file instead of stdout. There's nothing special about it, you could have done it normally on awk command as well. The use case arises when you need to redirect only a specific portion or if you need multiple redirections within the same awk command. Here's some examples of redirecting to multiple files.
$ seq 6 | awk 'NR%2{print > "odd.txt"; next} {print > "even.txt"}' $ cat odd.txt 1 3 5 $ cat even.txt 2 4 6 $ # dynamically creating filenames $ awk -v OFS='\t' 'NR>1{print $2, $3 > $1".txt"}' marks.txt $ # output for one of the departments $ cat ECE.txt Raj 53 Joel 72 Om 92
Note that the use of > doesn't mean that the file will get overwritten everytime. That happens only once if the file already existed prior to executing the awk command. Use >> if you wish to append to already existing files.
As seen in above examples, the file names are passed as string expressions. To redirect to a shell command, again you need to pass a string expression after | pipe symbol. Here's an example.
$ awk '{print $2 | "paste -sd,"}' table.txt bread,cake,banana
And here's some examples of multiple redirections.
$ awk '{print $2 | "sort | paste -sd,"}' table.txt banana,bread,cake $ # sort the output before writing to files $ awk -v OFS='\t' 'NR>1{print $2, $3 | "sort > "$1".txt"}' marks.txt $ # output for one of the departments $ cat ECE.txt Joel 72 Om 92 Raj 53
See gawk manual: Redirecting Output of print and printf for more details and operators on redirections. And see gawk manual: Closing Input and Output Redirections if you have too many redirections.
Summary
This chapter covered some of the built-in functions provided by awk. Do check the manual for more of them, for example math and time related functions.
Next chapter will cover features related to processing multiple files passed as input to awk.