The action part of the awk command is enclosed in curly braces. If no action is specified and a pattern is matched, awk takes the default action, which is to print the lines that are matched to the screen. The print function is used to print easy and simple output that does not require fancy formatting. For more sophisticated formatting, the printf or sprintf functions are used. If you are familiar with C, then you already know how printf and sprintf work.
The print function can also be explicitly used in the action part of awk as {print}. The print function accepts arguments as variables, computed values, or string constants. Strings must be enclosed in double quotes. Commas are used to separate the arguments; if commas are not provided, the arguments are concatenated together. The comma evaluates to the value of the output field separator (OFS), which is by default a space.
The output of the print function can be redirected or piped to another program, and the output of another program can piped to awk for printing. (See "Redirection" on page 22 and "Pipes" on page 25.)
% date Wed Jan 12 22:23:16 PST 2000 % date | awk '{ print "Month: " $2 " Year: " , $6 }' Month: Jan Year: 2000 |
Explanation
The output of the Linux date command will be piped to awk. The string Month: is printed, followed by the second field, the string containing the newline character, , and Year:, followed by the sixth field ($6).
Escape sequences are represented by a backslash and a letter or number. They can be used in strings to represent tabs, newlines, form feeds, and so forth (see Table 5.2).
Escape Sequence | Meaning |
---|---|
Backspace | |
f | Form feed |
Newline | |
Carriage return | |
Tab | |