【发布时间】:2012-05-15 05:54:14
【问题描述】:
如何在 Shell 脚本中提取匹配模式之后的任何字符串。我知道 Perl 脚本中的这个功能,但我不知道在 Shell 脚本中。
下面是例子,
Subject_01:这是一个示例主题,可能会有所不同
我必须提取“Subject_01:”之后的任何字符串
请帮忙。
【问题讨论】:
-
你用的是什么外壳?伯恩?长沙? KSH88? RC?
如何在 Shell 脚本中提取匹配模式之后的任何字符串。我知道 Perl 脚本中的这个功能,但我不知道在 Shell 脚本中。
下面是例子,
Subject_01:这是一个示例主题,可能会有所不同
我必须提取“Subject_01:”之后的任何字符串
请帮忙。
【问题讨论】:
这取决于你的外壳。
如果你使用bourne shell 或bash 或(我相信)pdksh,那么你可以做这样的花哨的事情:
$ 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),但我的大部分 shell 编程都是在 Bourne 中完成的。
【讨论】:
-f2-