sed extracting group of digits

前端 未结 5 1646
终归单人心
终归单人心 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

    It's because your first .* is greedy, and your [0-9]* allows 0 or more digits. Hence the .* gobbles up as much as it can (including the digits) and the [0-9]* matches nothing.

    You can do:

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

    where I forced the [0-9] to match at least one digit, and also added a word boundary before the digits so the whole number is matched.

    However, it's easier to use grep, where you match just the number:

    echo "This is an example: 65 apples" | grep -P -o '[0-9]+(?= +apples)'
    

    The -P means "perl regex" (so I don't have to worry about escaping the '+').

    The -o means "only print the matches".

    The (?= +apples) means match the digits followed by the word apples.

提交回复
热议问题