Table of Contents
AWK - AWK Patterns
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
Matching Patterns
To only print out lines which match a specific search criteria:
awk '/45/ {print $2,$4}' test.txt
returns:
Peter Roux Virginia Roux
NOTE: This only prints out the lines from the file which contained the number 45.
Multi-line Output with Patterns
To output onto multiple lines:
awk '/45/ {print $2,$3,$4 ; print $1, $5}' test.txt
returns:
Peter Terence Roux 10 45 Virginia Genevieve Roux 11 45
NOTE: 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
returns:
Peter Terence Roux 10 45 Virginia Genevieve 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
returns:
Peter Roux Virginia Roux David Stevenson Adam Ridley
NOTE: The pipe symbol | is used to provide multiple patterns.
Match against specific field
To restrict the match to only a specific field:
awk '$5 ~ /45|48/ {print $2,$4}' test.txt
returns:
Peter Roux Virginia Roux David Stevenson
NOTE: 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:
awk '$5 !~ /45|48/ {print $2,$4}' test.txt
returns:
Felix Roux Bob Smith Adam Ridley
NOTE: 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:
awk '/4[2-8]/ {print $2,$4}' test.txt
returns:
Peter Roux Virginia Roux David Stevenson Adam Ridley
NOTE: This finds all fields with values between 42 and 48.