Assuming a file, test.txt exists with the following contents:
10 Peter Terence Roux 45 11 Virginia Genevieve Roux 45 12 Felix Devon Roux 5 13 David Bruce Stevenson 48 14 Bob James Smith 16 48 Adam Winter Ridley 23
Multiple commands can be passed together.
awk '/45/ {print $2,$3,$4} {print $1": "$5"\n"}' test.txt
returns:
Peter Terence Roux 10: 45 Virginia Genevieve Roux 11: 45 12: 5 13: 48 14: 16 48: 23
NOTE: This inserts a colon and a space and comma between $1 and $5.
It also inserts new line after each two-line display.
Certain escape sequences are supported, including:
Character | Details |
---|---|
\\ | A literal backslash. |
\b | Backspace. |
\f | Formfeed. |
\n | New line. |
\r | Carriage return. |
\t | Horizontal tab. |
\v | Vertical tab. |
\xhh | Hex digits where hh represents the hex digits. E.g. \x2F |
Additional text can be added to lines.
awk '/45/ {print "NAME: "$2,$3,$4 "\tAGE: "$5}' test.txt
returns:
NAME: Peter Terence Roux AGE: 45 NAME: Virginia Genevieve Roux AGE: 45
NOTE: The values between double quotes can be anything.
awk '/45/ {printf ("%s %d %x %s\n", $2,$5,$5,"x")}' test.txt
returns:
Peter 45 2d x Virginia 45 2d x
NOTE: The printf command can be used to handle more complex output requirements.
This is the list of specifications supported by the printf command:
Specification | Details |
---|---|
%c | Prints a single ASCII character. |
%d | Prints a decimal number. |
%e | Prints a scientific notation representation of numbers. |
%f | Prints a floating-point representation. |
%g | Prints %e or %f; whichever is shorter. |
%o | Prints an unsigned octal number. |
%s | Prints an ASCII string. |
%x | Prints an unsigned hexadecimal number. |
%% | Prints a percent sign; no conversion is performed. |