DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
Programming with awk

Output to files

You can print output to files instead of to the standard output by using the > and >> redirection operators. For example, the following program invoked on the file countries prints all lines where the population (third field) is bigger than 100 into a file called bigpop, and all other lines into a file called smallpop:

   $3 > 100   { print $1, $3 >"bigpop" }
   $3 <= 100  { print $1, $3 >"smallpop" }
Notice that the filenames have to be quoted; without quotes, bigpop and smallpop are merely uninitialized variables. If the output filenames were created by an expression, they would also have to be enclosed in parentheses:
   $4 ~ /North America/ { print $1 > ("tmp" FILENAME) }
because the > operator has higher precedence than concatenation; without parentheses, the concatenation of tmp and FILENAME would not work.


NOTE: Files are opened once in an awk program. If > is used to open a file, its original contents are overwritten. But if >> is used to open a file, its contents are preserved and the output is appended to the file. Once the file has been opened, the two operators have the same effect.


Next topic: Output to pipes
Previous topic: awk printf conversion characters

© 2004 The SCO Group, Inc. All rights reserved.
UnixWare 7 Release 7.1.4 - 27 April 2004