11.0 Interacting with the Shell: I/O Redirection
11.1. Managing Output Streams
While printing to the standard output is the default behavior, real-world scripts often need to save results to files for persistence or pass data to other command-line tools for further processing. I/O redirection is AWK’s mechanism for managing these output streams directly from within a script.
11.2. Output to Files
Overwrite Operator ()
This operator directs the output of a print or printf statement to a file. If the file does not exist, it is created. If it does exist, its contents are overwritten.
- Syntax: print DATA > output-file
# This command will overwrite /tmp/message.txt
[jerry]$ awk ‘BEGIN { print “Hello, World !!!” > “/tmp/message.txt” }’
Append Operator ()
This operator also directs output to a file, but it appends the new data to the end of the file, preserving any existing content.
- Syntax: print DATA >> output-file
# This command will add a new line to /tmp/message.txt
[jerry]$ awk ‘BEGIN { print “Hello, World !!!” >> “/tmp/message.txt” }’
11.3. Piping to External Commands
One-Way Pipe ()
The pipe operator sends the output of a print or printf statement as the standard input to another shell command.
- Syntax: print items | command
This example pipes a string to the tr command to convert it to uppercase.
[jerry]$ awk ‘BEGIN { print “hello, world !!!” | “tr [a-z] [A-Z]” }’
Output:
HELLO, WORLD !!!
Two-Way Communication ()
AWK can also establish a two-way pipe with an external command, creating a co-process. This allows a script to both send data to and receive data from the command.
Consider the following script, command.awk:
BEGIN {
cmd = “tr [a-z] [A-Z]”
print “hello, world !!!” |& cmd
close(cmd, “to”)
cmd |& getline out
print out;
close(cmd);
}
Execution Analysis:
- cmd = “tr …”: A variable stores the command string.
- print … |& cmd: The string “hello, world !!!” is sent to the tr command’s standard input.
- close(cmd, “to”): The “to” part of the co-process stream is closed, signaling to tr that there is no more input.
- cmd |& getline out: AWK reads one line of output from the tr command and stores it in the out variable.
- print out: The contents of out are printed to standard output.
- close(cmd): The co-process is fully closed.
Output:
HELLO, WORLD !!!
Whether output is sent to a file or the screen, it is often necessary to format it precisely, which is the role of the printf function.