How to print matched regex pattern using awk?

后端 未结 8 684
说谎
说谎 2020-11-29 15:56

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

8条回答
  •  忘掉有多难
    2020-11-29 16:44

    It sounds like you are trying to emulate GNU's grep -o behaviour. This will do that providing you only want the first match on each line:

    awk 'match($0, /regex/) {
        print substr($0, RSTART, RLENGTH)
    }
    ' file
    

    Here's an example, using GNU's awk implementation (gawk):

    awk 'match($0, /a.t/) {
        print substr($0, RSTART, RLENGTH)
    }
    ' /usr/share/dict/words | head
    act
    act
    act
    act
    aft
    ant
    apt
    art
    art
    art
    

    Read about match, substr, RSTART and RLENGTH in the awk manual.

    After that you may wish to extend this to deal with multiple matches on the same line.

提交回复
热议问题