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

Output to pipes

You can also direct printing to a pipe with a command on the other end, instead of to a file. The statement

   print | "command-line"
causes the output of print to be piped into the command-line.

Although they are shown here as literal strings enclosed in quotes, the command-line and filenames can come from variables and the return values from functions.

Suppose you want to create a list of continent-population pairs, sorted alphabetically by continent. The awk program below accumulates the population values in the third field for each of the distinct continent names in the fourth field in an array called pop. Then it prints each continent and its population, and pipes this output into the sort command.

   BEGIN   { FS = "\t" }
           { pop[$4] += $3 }
   END     { for (c in pop)
                print c ":" pop[c] | "sort" }
Invoked on the file countries, this program yields
   Africa:37
   Asia:1765
   Australia:14
   North America:243
   South America:142

In all these print statements involving redirection of output, the files or pipes are identified by their names (that is, the pipe above is literally named sort ), but they are created and opened only once in the entire run. So, in the last example, for all c in pop, only one sort pipe is open.

There is a limit to the number of files that can be open simultaneously. The statement close(file) closes a file or pipe; file is the string used to create it in the first place, as in

   close("sort")
When opening or closing a file, different strings are different commands.
Next topic: Input
Previous topic: Output to files

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