PYPL
PYPL

Reputation: 1849

Parsing a string with sed

I have a string like prefix-2020.80-suffix-1 Here are all of possible combinations of input string

"2020.80-suffix-1"
"2020.80-suffix"
"prefix-2020.80"
"prefix-2020.80-1"

I need to cut out and assign 2020 to a variable but cannot get my desired output

Here what i got so far...

set var=`echo "prefix-2020.80-suffix-1" | sed "s/[[:alnum:]]*-*\([0-9]*\).*/\1/"`

My regexp does not work for other cases and i cannot figure out why! its more complicated that python's regexp syntax

Upvotes: 0

Views: 128

Answers (3)

Jahid
Jahid

Reputation: 22428

Using sed (with extended regex):

echo "prefix-2020.80-suffix-1" |sed -r 's/^([^-]*-|)([0-9]+).*/\2/'

Using grep:

echo "prefix-2020.80-suffix-1" |grep -oP "^([^-]*-|)\K\d+"
2020

-P is for Perl regex.

Upvotes: 0

anubhava
anubhava

Reputation: 785186

You can use this grep -oP:

echo "prefix-2020.80-suffix-1" | grep -oP '^([[:alnum:]]+-)?\K[0-9]+'
2020

RegEx Demo

Upvotes: 0

123
123

Reputation: 11216

This should work for all you inputs

sed 's/.*\(^\|-\)\([0-9]*\)\..*/\2/' test

Matches the start of the line or everything up to -[number]. and captures the number.

The problem with the original you were using was you didn't take into account when there wasn't a prefix.

Upvotes: 1

Related Questions