6.15. Pipes

 <  Day Day Up  >  

If you open a pipe in an awk program, you must close it before opening another one. The command on the right-hand side of the pipe symbol is enclosed in double quotes. Only one pipe can be open at a time.

Example 6.102.
 (The Database) %  cat names   john smith   alice cheba   george goldberg   susan goldberg   tony tram   barbara nguyen   elizabeth lone   dan savage   eliza goldberg   john goldenrod  (The Command Line) %  nawk '{print ,   "sort r +1 2 +0 1 "}' names  (The Output)  tony tram   john smith   dan savage   barbara nguyen   elizabeth lone   john goldenrod   susan goldberg   george goldberg   eliza goldberg   alice cheba  

EXPLANATION

Awk will pipe the output of the print statement as input to the UNIX/Linux sort command, which does a reversed sort using the second field as the primary key and the first field as the secondary key (i.e., sort by last name in reverse). The UNIX/Linux command must be enclosed in double quotes. (See "sort" in Appendix A.)

6.15.1 Closing Files and Pipes

If you plan to use a file or pipe in an awk program again for reading or writing, you may want to close it first, because it remains open until the script ends. Once opened, the pipe remains open until awk exits. Therefore, statements in the END block will also be affected by the pipe. The first line in the END block closes the pipe.

Example 6.103.
 (In Script) 1  { print , ,   " sort -r +1 -2 +0 -1"}  END{ 2  close("sort r +1 2 +0 1")  <rest of statements>  } 

EXPLANATION

  1. Awk pipes each line from the input file to the UNIX/Linux sort utility.

  2. When the END block is reached, the pipe is closed. The string enclosed in double quotes must be identical to the pipe string where the pipe was initially opened.

The system Function

The built-in system function takes a UNIX/Linux system command as its argument, executes the command, and returns the exit status to the awk program. It is similar to the C standard library function, also called system() . The UNIX/Linux command must be enclosed in double quotes.

FORMAT

 system("UNIX/Linux Command") 

Example 6.104.
 (In Script)  {  1  system ("cat")  2  system ("clear")   }  

EXPLANATION

  1. The system function takes the UNIX/Linux cat command and the value of the first field in the input file as its arguments. The cat command takes the value of the first field, a filename, as its argument. The UNIX/Linux shell causes the cat command to be executed.

  2. The system function takes the UNIX/Linux clear command as its argument. The shell executes the command, causing the screen to be cleared.

 <  Day Day Up  >  


UNIX Shells by Example
UNIX Shells by Example (4th Edition)
ISBN: 013147572X
EAN: 2147483647
Year: 2004
Pages: 454
Authors: Ellie Quigley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net