Jill
Jill

Reputation: 33

How to extract substring from string

I have a string, that does not always look the same, and from this string I want to extract some information if it exists. The string might look like one of the following:

myCommand -s 12 moreParameters
myCommand -s12 moreParamaters
myCommand -s moreParameters

I want to get the number, i.e. 12 in this case, if it exists. How can I accomplish that?

Many thanks!

EDIT: There is a fourth possible value for the string:

myCommand moreParameters

How can I modify the regex to cover this case as well?

Upvotes: 2

Views: 2829

Answers (3)

bash-o-logist
bash-o-logist

Reputation: 6911

You can do all these without the need for external tools

$ shopt -s extglob
$ string="myCommand -s 12 moreParameters"
$ string="${string##*-s+( )}"
$ echo "${string%% *}"
12

Upvotes: 1

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99879

Try this:

n=$(echo "$string"|sed 's/^.*-s *\([0-9]*\).*$/\1/')

This will match a -s eventually followed by spaces and digits; and replace the whole string by the digits.

myCommand -s 12 moreParameters => 12
myCommand -s12 moreParamaters  => 12
myCommand -s moreParameters    => empty string

EDIT: There is a fourth possible value for the string:

myCommand moreParameters

How can I modify the regex to cover this case as well?

Upvotes: 1

Fredrik Pihl
Fredrik Pihl

Reputation: 45634

$ a="myCommand -s 12 moreParameters"
$ b="myCommand -s12 moreParamaters"
$ echo $(expr "$a" : '[^0-9]*\([0-9]*\)')
12
$ echo $(expr "$b" : '[^0-9]*\([0-9]*\)')
12

Upvotes: 2

Related Questions