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

后端 未结 11 489
长情又很酷
长情又很酷 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:35

    If you want to select lines then strip out the bits you don't want:

    egrep 'abc[0-9]+xyz' inputFile | sed -e 's/^.*abc//' -e 's/xyz.*$//'
    

    It basically selects the lines you want with egrep and then uses sed to strip off the bits before and after the number.

    You can see this in action here:

    pax> echo 'a
    b
    c
    abc12345xyz
    a
    b
    c' | egrep 'abc[0-9]+xyz' | sed -e 's/^.*abc//' -e 's/xyz.*$//'
    12345
    pax> 
    

    Update: obviously if you actual situation is more complex, the REs will need to me modified. For example if you always had a single number buried within zero or more non-numerics at the start and end:

    egrep '[^0-9]*[0-9]+[^0-9]*$' inputFile | sed -e 's/^[^0-9]*//' -e 's/[^0-9]*$//'
    

提交回复
热议问题