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?

0

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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?

3 Comments

Thank you so much for a quick response. Much appreciated!
in bash, you can use "here-strings": n=$(sed 's/^.*-s *\([0-9]*\).*$/\1/' <<< "$string")
You can handle the additional case e.g. by only printing matching lines. sed -n 's/^.*-s *\([0-9]*\).*$/\1/p'
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.