This is an old revision of the document!
Table of Contents
AWK - AWK Patterns
Assuming a file exists with the following contents:
10 Peter Terence Roux 45 11 Virginia Genevive Roux 45 12 Felix Devon Roux 5 13 David Bruce Stevenson 48 14 Bob James Smith 16 48 Adam Winter Ridley 23
Matching Patterns
To only print out lines which match a specific search criteria, issue the following command:
awk '/45/ {print $2,$4}' test.txt
which will display something like:
Peter Roux Virginia Roux
This only prints out the lines from the file which contained the number 45.
Multi-line Output with Patterns
To output onto multiple lines, issue the following command:
awk '/45/ {print $2,$3,$4 ; print $1, $5}' test.txt
which will display something like:
Peter Terence Roux 10 45 Virginia Genevive Roux 11 45
Again, this only prints out the lines from the file which contained the number 45.
But also prints out a 2nd line because of the use of the semicolon.
NOTE: A semicolon does not have to be used to allow using multiple commands.
For instance issue the following command instead:
awk '/45/ {print $2,$3,$4} {print $1, $5}' test.txt
which will display something like:
Peter Terence Roux 10 45 Virginia Genevive Roux 11 45 12 5 13 48 14 16 48 23
This time an altogether different result is produced, than when a semicolon was used.
The reason for this is that the pattern that is used, /45/ is only applied to the command immediately following it. In this example, this was only against fields $2, $3 and $4.
The 2nd print statement is not affected by the pattern and would apply to all fields in the input file.
Match using Multiple Patterns
To search for more than one pattern match at a time, issue the following command:
awk '/45|48/ {print $2,$4}' test.txt
which will display something like:
Peter Roux Virginia Roux David Stevenson Adam Ridley
The pipe symbol | is used to provide multiple patterns.
Match against specific field
To restrict the match to only a specific field, issue the following command:
awk '$5 ~ /45|48/ {print $2,$4}' /sharewiz/awk/test.txt
which will display something like:
Peter Roux Virginia Roux David Stevenson
Note that this time Adam Ridley is not displayed even though the source file has a 48 as part of his record.
The tilda ~ ties the match to a specific field.
Match not against a specific field
To have the match be the opposite of matching a specific field, issue the following command:
awk '$5 !~ /45|48/ {print $2,$4}' test.txt
which will display something like:
Felix Roux Bob Smith Adam Ridley
The exclamation mark and tilda (!~) together informs to not match to a specific field.
Match in a Range
To have the match be the opposite of matching a specific field, issue the following command:
awk '/4[2-8]/ {print $2,$4}' /sharewiz/awk/test.txt
which will display something like:
Peter Roux Virginia Roux David Stevenson Adam Ridley
This finds all fields with values between 42 and 48.