在Shell中匹配模式后提取字符串

时间:2012-05-15 05:54:14

标签: regex shell

如何在Shell脚本中的匹配模式之后提取任何字符串。我在Perl脚本中知道这个功能,但我不知道在Shell脚本中。

以下是示例,

  

Subject_01:这是一个样本主题,可能会有所不同

我必须提取“Subject_01:”之后的任何字符串

请帮助。

1 个答案:

答案 0 :(得分:3)

这取决于你的shell。

如果你正在使用 shell或或(我相信),那么你可以做这样的花哨的东西:

$ string="Subject_01: This is a sample subject and this may vary"
$ output="${string#*: }"
$ echo $output
This is a sample subject and this may vary
$

请注意,这在格式方面非常有限。上面的行要求你的冒号后有一个空格。如果你有更多,它将填充$output

的开头

如果您正在使用其他shell,则可能必须使用cut命令执行此类操作:

> setenv string "Subject_01: This is a sample subject and this may vary"
> setenv output "`echo '$string' | cut -d: -f2`"
> echo $output
This is a sample subject and this may vary
> setenv output "`echo '$string' | sed 's/^[^:]*: *//'`"
> echo $output
This is a sample subject and this may vary
> 

第一个示例使用cut,这非常小而且简单。第二个例子使用sed,它可以做得更多,但就CPU而言(非常)稍微重一点。

YMMV。在csh中可能有更好的方法来处理这个问题(我的第二个例子使用了tcsh),但我在Bourne中进行了大部分shell编程。