Directing Output to Files and Pipes

The output of any print or printf statement can be directed to a file, using the output redirection operators “>” or “>>”. For example, the following statement writes the current record to the file data.out:

print > "data.out"

The filename can be any expression that evaluates to a valid filename. A file is opened by the first use of the redirection operator, and subsequent uses append data to the file. The difference between “>” and “>>” is the same as between the shell redirection operators. A right-angle bracket (“>”) truncates the file when opening it while “>>” preserves whatever the file contains and appends data to it.

Because the redirection operator “>” is the same as the relational operator, there is the potential for confusion when you specify an expression as an argument to the print command. The rule is that “>” will be interpreted as a redirection operator when it appears in an argument list for any of the print statements. To use “>” as a relational operator in an expression that appears in the argument list, put either the expression or the argument list in parentheses. For example, the following example uses parentheses around the conditional expression to make sure that the relational expression is evaluated properly:

print "a =", a, "b =", b, "max =", (a > b ? a : b) > "data.out"

The conditional expression evaluates whether a is greater than b; if it is, then the value of a is printed as the maximum value; otherwise, b’s ...

Get sed & awk, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.