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?
$ 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
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?
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
精彩评论