An Awk Primer/Output Redirection and Pipes

Output redirection operator
The output-redirection operator "&gt;" can be used in Awk output statements. For example: print 3 &gt; "tfile" —creates a file named "tfile" containing the number "3". If "tfile" already exists, its contents are overwritten.

If you print more things into the same file, its contents will not be overwritten anymore. For example, after running the following code print "How doth the little crocodile" &gt; "poem" print "   Improve his shining tail," &gt; "poem" print "And pour the waters of the Nile" &gt; "poem" print "    On every golden scale!" &gt; "poem" the file "poem" will contain the following How doth the little crocodile Improve his shining tail, And pour the waters of the Nile On every golden scale!

Append redirection operator
The "append" redirection operator ("&gt;&gt;"), which can be used in exactly the same way, never overwrites files. For example: print 4 &gt;&gt; "tfile" —tacks the number "4" to the end of "tfile". If "tfile" doesn't exist, it is created and the number "4" is appended to it.

Using redirection with printf
Output and append redirection can be used with "printf" as well. For example: BEGIN {for (x=1; x&lt;=50; ++x) {printf("%3d\n",x) &gt;&gt; "tfile"}} —dumps the numbers from 1 to 50 into "tfile".

Pipe
The output can also be "piped" into another utility with the "|" ("pipe") operator. As a trivial example, we could pipe output to the "tr" ("translate") utility to convert it to upper-case: print "This is a test!" | "tr [a-z] [A-Z]"

This yields: THIS IS A TEST!

Closing a file
You can close a file with function close(file)

There is a limit on the number of files opened simultaneously (under Linux, a typical limit is 1024), so you may want to close files which you don't need anymore.

Beware! If you close a file and then print to that file again, the system would erase whatever you printed before, as it treats it as a new file. For example, after

{ print "How doth the little crocodile" > "poem" print "   Improve his shining tail," > "poem" print "And pour the waters of the Nile" > "poem" print "    On every golden scale!" > "poem" close("poem") print "     Lewis Carroll" > "poem" }

The file "poem" will contain just one line: Lewis Carroll

Never output anything into a file after you closed it!

After a file is closed, you may only append into it.