How can I use sed to regex string and number in bash script

I want to separate string and number in a file to get a specific number in bash script, such as:

Branches executed:75.38% of 1190

I want to only get number

75.38

. I have try like the code below

$new_value=value | sed -r 's/.*_([0-9]*)\..*/\1/g'

but it was incorrect and it was failed.

How should it works? Thank you before for your help.

Upvotes: 2

Views: 80

Answers (3)

Tamas Rev
Tamas Rev

Reputation: 7166

There are several things here that we could improve. One is that you need to escape the parentheses in sed: \(...\)

Another one is that it would be good to have a full specification of the input strings as well as a good script that can help us to play with this.

Anyway, this is my first attempt: Update: I added a little more bash around this regex so it'll be more easy to play with it:

value='Branches executed:75.38% of 1190'
new_value=`echo $value | sed -e 's/[^0-9]*\([0-9]*\.[0-9]*\).*/\1/g'`
echo $new_value

Update 2: as john pointed out, it will match only numbers that contain a decimal dot. We can fix it with an optional group: \(\.[0-9]\+\)?. An explanation for the optional group:

  • \(...\) is a group.
  • \(...\)? Is a group that appears zero or one times (mind the question mark).
  • \.[0-9]\+ is the pattern for a dot and one or more digits.

Putting all together:

value='Branches executed:75.38% of 1190'
new_value=`echo $value | sed -e 's/[^0-9]*\([0-9]\+\(\.[0-9]\+\)\?\).*/\1/g'`
echo $new_value

Upvotes: 0

Jay jargot
Jay jargot

Reputation: 2868

Give this a try:

value=$(sed "s/^Branches executed:\([0-9][.0-9]*[0-9]*\)%.*$/\1/" afile)

It is assumed that the line appears only once in afile.

The value is stored in the value variable.

Upvotes: 1

Andreas Louv
Andreas Louv

Reputation: 47099

You can use the following regex to extract the first number in a line:

^[^0-9]*\([0-9.]*\).*$

Usage:

% echo 'Branches executed:75.38% of 1190' | sed 's/^[^0-9]*\([0-9.]*\).*$/\1/'
75.38

Upvotes: 1

Related Questions