2

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?

Liz
  • 625
  • 4
  • 9
  • 14
Jill
  • 33
  • 1
  • 3

3 Answers3

2
$ 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
Fredrik Pihl
  • 44,604
  • 7
  • 83
  • 130
1

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?

Liz
  • 625
  • 4
  • 9
  • 14
Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
1

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
bash-o-logist
  • 6,665
  • 1
  • 17
  • 14