An Awk Primer/Output Redirection and Pipes

Output redirection operator

edit

The output-redirection operator ">" can be used in Awk output statements. For example:

   print 3 > "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" > "poem"
print "    Improve his shining tail," > "poem"
print "And pour the waters of the Nile" > "poem"
print "     On every golden scale!" > "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

edit

The "append" redirection operator (">>"), which can be used in exactly the same way, never overwrites files. For example:

   print 4 >> "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

edit

Output and append redirection can be used with "printf" as well. For example:

   BEGIN {for (x=1; x<=50; ++x) {printf("%3d\n",x) >> "tfile"}}

—dumps the numbers from 1 to 50 into "tfile".

Pipe

edit

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

edit

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.