7.4. 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 opened 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 7.17.
(In Script)
1   { print $1, $2, $3 | " 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 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 Linux (operating system command) 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 Linux command must be enclosed in double quotes. If the system function (gawk only) is given an empty string as its argument, the output buffers will be flushed.

Format

system( "Linux Command")

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

Explanation

  1. The system function takes the UNIX 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 shell causes the cat command to be executed.

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

The fflush Function

The fflush function was added to awk in 1994 (Bell Labs) and is not included in the POSIX standard. Gawk uses it to flush output buffers. If fflush is not given an argument, it flushes the buffer for standard output. If the null string is given as an argument, e.g., fflush(“ “), the buffers for all open files and pipes are flushed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.37.10