how to use sed, awk, or gawk to print only what is matched?

后端 未结 11 714
长情又很酷
长情又很酷 2021-01-30 05:59

I see lots of examples and man pages on how to do things like search-and-replace using sed, awk, or gawk.

But in my case, I have a regular expression that I want to run

11条回答
  •  清歌不尽
    2021-01-30 06:52

    You can use awk with match() to access the captured group:

    $ awk 'match($0, /abc([0-9]+)xyz/, matches) {print matches[1]}' file
    12345
    

    This tries to match the pattern abc[0-9]+xyz. If it does so, it stores its slices in the array matches, whose first item is the block [0-9]+. Since match() returns the character position, or index, of where that substring begins (1, if it starts at the beginning of string), it triggers the print action.


    With grep you can use a look-behind and look-ahead:

    $ grep -oP '(?<=abc)[0-9]+(?=xyz)' file
    12345
    
    $ grep -oP 'abc\K[0-9]+(?=xyz)' file
    12345
    

    This checks the pattern [0-9]+ when it occurs within abc and xyz and just prints the digits.

提交回复
热议问题