【问题标题】:Extracting string after matched pattern in Shell在Shell中匹配模式后提取字符串
【发布时间】:2012-05-15 05:54:14
【问题描述】:

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

下面是例子,

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

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

请帮忙。

【问题讨论】:

标签: regex shell


【解决方案1】:

这取决于你的外壳。

如果你使用 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),但我的大部分 shell 编程都是在 Bourne 中完成的。

【讨论】:

  • 对于剪切,如果您只想删除第一个字段(以防字符串的其余部分有冒号),请使用-f2-
  • @glennjackman - 是的,感谢您指出这一点。该符号将返回该行的其余部分,甚至包括后续冒号周围的空格,尽管它仍然不允许我们在开头修剪空格。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-10
  • 1970-01-01
  • 1970-01-01
  • 2019-05-27
  • 1970-01-01
  • 2010-10-27
相关资源
最近更新 更多