awk awk

awk Regex Comparisons

What if we aren't sure of the spelling of our search term? In the previous example, is it 'Gerry' or 'Jerry'?

Luckily awk has ways of dealing with this. We have already seen the 'equality' operator ==.

To solve our problem above, we could do something like this:

awk '{FS = ":"} $1 ~ "erry" {print $1, $2}' names.txt

Interpreted, that means 'If the first field of a line matches 'erry', print the first and second fields, of each line in the file 'names.txt'

Which would give us:

Or what if we were looking at a scrawled signature on an invoice, and could only work out the last few letters of the first name?

awk '{FS = ":"} $1 ~ "ry" {print $1,$2}' names.txt