How to print matched regex pattern using awk?

marverix picture marverix · Apr 4, 2011 · Viewed 467.3k times · Source

Using awk, I need to find a word in a file that matches a regex pattern.

I only want to print the word matched with the pattern.

So if in the line, I have:

xxx yyy zzz

And pattern:

/yyy/

I want to only get:

yyy

EDIT: thanks to kurumi i managed to write something like this:

awk '{
        for(i=1; i<=NF; i++) {
                tmp=match($i, /[0-9]..?.?[^A-Za-z0-9]/)
                if(tmp) {
                        print $i
                }
        }
}' $1

and this is what i needed :) thanks a lot!

Answer

kurumi picture kurumi · Apr 4, 2011

This is the very basic

awk '/pattern/{ print $0 }' file

ask awk to search for pattern using //, then print out the line, which by default is called a record, denoted by $0. At least read up the documentation.

If you only want to get print out the matched word.

awk '{for(i=1;i<=NF;i++){ if($i=="yyy"){print $i} } }' file