Table of Contents

AWK - AWK Output

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

Display Tidy Output

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:

CharacterDetails
\\A literal backslash.
\bBackspace.
\fFormfeed.
\nNew line.
\rCarriage return.
\tHorizontal tab.
\vVertical tab.
\xhhHex digits where hh represents the hex digits. E.g. \x2F

Adding Text

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.


Advanced Text Output

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:

SpecificationDetails
%cPrints a single ASCII character.
%dPrints a decimal number.
%ePrints a scientific notation representation of numbers.
%fPrints a floating-point representation.
%gPrints %e or %f; whichever is shorter.
%oPrints an unsigned octal number.
%sPrints an ASCII string.
%xPrints an unsigned hexadecimal number.
%%Prints a percent sign; no conversion is performed.