An Awk Primer/Output Redirection and Pipes

From Wikibooks, open books for an open world
Jump to: navigation, search

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. The "append" redirection operator (">>") can be used in exactly the same way. 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.


Output 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".


  • 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!