如何从字符串中提取子字符串

时间:2011-09-14 20:11:27

标签: bash sed grep substring extract

我有一个字符串,并不总是看起来一样,从这个字符串我想提取一些信息(如果它存在)。该字符串可能如下所示:

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

我想得到这个数字,即在这种情况下是12,如果存在的话。我怎么能做到这一点?

非常感谢!

编辑:字符串有第四个可能的值:

myCommand moreParameters

如何修改正则表达式以涵盖此案例?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

试试这个:

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

这将匹配-s,最后是空格和数字;并用数字替换整个字符串。

  

myCommand -s 12 moreParameters => 12个
  myCommand -s12 moreParamaters  => 12个
  myCommand -s moreParameters    =>空字符串

编辑:字符串有第四个可能的值:

myCommand moreParameters

如何修改正则表达式以涵盖此案例?

答案 2 :(得分:1)

您可以在不需要外部工具的情况下完成所有这些工作

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