sed extracting group of digits

前端 未结 5 1647
终归单人心
终归单人心 2021-02-18 15:18

I have tried to extract a number as given below but nothing is printed on screen:

echo \"This is an example: 65 apples\" | sed -n  \'s/.*\\([0-9]*\\) apples/\\1/         


        
5条回答
  •  无人及你
    2021-02-18 16:10

    What you are seeing is the greedy behavior of regex. In your first example, .* gobbles up all the digits. Something like this does it:

    echo "This is an example: 65144 apples" | sed -n  's/[^0-9]*\([0-9]\+\) apples/\1/p'
    65144
    

    This way, you can't match any digits in the first bit. Some regex dialects have a way to ask for non-greedy matching, but I don't believe sed has one.

提交回复
热议问题