Strive
Strive

Reputation: 73

Why sed extended regex with plus sign is not working

I have to fetch major and minor version combined together as one number in bash script.

For example: From 'Python 3.10.2', I need 310

sed 's/.* \([0-9]\).\([0-9]\).*/\1\2/' works perfectly when the minor version is single digit and it fails when it is double digit. Hence, i tried sed -E 's/.* \([0-9]+\).\([0-9]+\).*/\1\2/'. But this throws an error

for example: echo "Python 3.10.2" | sed -E 's/.* \([0-9]+\).\([0-9]+\).*/\1\2/' results in an error

As a workaround, i am using echo "Python 3.10.2" | grep -Eo '[0-9]+.[0-9]+' | sed s/[.]//g

Is there a way to get what i need in one sed without using grep like how i am doing currently?

Thanks,

Strive

Upvotes: 1

Views: 330

Answers (2)

Ed Morton
Ed Morton

Reputation: 203655

You're probably getting an error message about \1 and \2 not being available/populated since in this code:

echo "Python 3.10.2" | sed -E 's/.* \([0-9]+\).\([0-9]+\).*/\1\2/'

you're escaping the ( and ) that would populate those cap[ture groups. You need to escape them in BREs, but you're using EREs, courtesy of -E and so you have to leave them unescaped:

$ echo "Python 3.10.2" | sed -E 's/.* ([0-9]+).([0-9]+).*/\1\2/'
310

The . in the middle of the regexp should really be escaped as \.

Upvotes: 1

ahmedazhar05
ahmedazhar05

Reputation: 618

This is probably what you want:

sed -E 's/^.+ |\.[0-9]*$|\.//g'

this removes everything from

  1. the beginning uptil a space
  2. the end after and including the last dot .
  3. removes every dot . in between

Upvotes: 1

Related Questions