User Tools

Site Tools


awk:awk_fields

AWK - AWK Fields

Assuming a file 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

Understanding Fields

awk '{print $1,$2,$3,$4,$5}' test.txt

returns:

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

NOTE: AWK has read each field in the file into the variables $1, $2, $3, etc.

  • Each field is split by a field separator, which by default is a space or comma.
    • As can be seen, it does not matter how many spaces separate each field in the input file.
  • As AWK reads the input, the entire record is assigned to the variable $0.

Display Only Certain Fields

To only print the name and surname, i.e. fields $2 and $4:

awk '{print $2,$4}' test.txt

returns:

Peter Roux
Virginia Roux
Felix Roux
David Stevenson
Bob Smith
Adam Ridley

The ability to address each field with a unique number allows only specific fields to be output.

NOTE : Fields can be printed out in any order. For example:

awk '{print $4,$2}' test.txt

returns:

Roux Peter
Roux Virginia
Roux Felix
Stevenson David
Smith Bob
Ridley Adam

Notice that the surname is now printed before first name.


Display Multi-line Output

To output onto multiple lines:

awk '{print $2,$3,$4; print $1, $5}' test.txt

returns:

Peter Terence Roux
10 45
Virginia Genevieve Roux
11 45
Felix Devon Roux
12 5
David Bruce Stevenson
13 48
Bob James Smith
14 16
Adam Winter Ridley
48 23

NOTE: The semicolon (;) indicates to write some data to a different line.

This could also be written as the following, which will produce the same results:

awk '{print $2,$3,$4} {print $1, $5}' test.txt

WARNING: Although both uses of code produce the same result here, be warned that they can produce different results when used with more advanced AWK options.


awk/awk_fields.txt · Last modified: 2022/06/13 10:37 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki