UNIX & GNU/Linux - awk - Using matching expressions and operators to find a pattern

The user command awk enables to check if an expression could be found in a file.

It's a kind of regex, with classic operators, such as: ? . *.

Let's do it.

Explanation

We would like to find every line where there is an "e" followed by any character and a "4".
For example, the following line matches the pattern.:

awdawekoodk d ekokd 93239 93994543z k

To find it, we have to use ($0 ~/e.*4/) because we tell that we want that in each column of the file ($0), we would like to find the pattern "e.*4".
For that we use the tilde (~) and slashes (/) at the beginning and at the end of our pattern.

Don't forget that we are searching a lowercase "e", so the uppercase won't match it.

Code

customers.txt

Georges William 12-2-1967 M 1895602
John Maynard 7-4-1944 W 981502
Wolfgang Amadeus 3-11-1938 M 64158674102
Ludwig SCHMILL 11-28-1957 M 5648510
Antonio VAVILDA 5-16-1937 M
Hugues Ofrette 8-11-1958 M 4515660
Dagobert ELOY 7-14-1905 M 0225415487

Akio Shamiwara 1-2-1965 n 4
Antonio SZWPRESWKY 16-5-8937 M 0298358745

bp4.awk

#!/bin/awk

# Begin
BEGIN {
    FS=" ";
};

# Dev
{
    if ($0 ~/e.*4/) {
        print $0
    }
}

# End
END {}

Execution

awk -f bp4.awk customers.txt

Output

Wolfgang Amadeus 3-11-1938 M 64158674102
Hugues Ofrette 8-11-1958 M 4515660
Dagobert ELOY 7-14-1905 M 0225415487

Finally

You've made it.
Well done. wink

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.