How to print matched regex pattern using awk?

后端 未结 8 638
说谎
说谎 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:51

    Off topic, this can be done using the grep also, just posting it here in case if anyone is looking for grep solution

    echo 'xxx yyy zzze ' | grep -oE 'yyy'
    
    0 讨论(0)
  • 2020-11-29 16:51

    If you know what column the text/pattern you're looking for (e.g. "yyy") is in, you can just check that specific column to see if it matches, and print it.

    For example, given a file with the following contents, (called asdf.txt)

    xxx yyy zzz
    

    to only print the second column if it matches the pattern "yyy", you could do something like this:

    awk '$2 ~ /yyy/ {print $2}' asdf.txt
    

    Note that this will also match basically any line where the second column has a "yyy" in it, like these:

    xxx yyyz zzz
    xxx zyyyz
    
    0 讨论(0)
提交回复
热议问题