首页 > 解决方案 > 正确的 bash sed 命令语法以获取正确的子字符串

问题描述

试图从 a 中获取子字符串:

foo-bar-8568887b6f-d95wk 1/1 跑步 0 48m

得到一个: foo-bar-8568887b6f-d95wk

使用: sed 's/^.\((foo-bar)[^\s]+\).*$/\1/'

但是,这将返回整个字符串: foo-bar-8568887b6f-d95wk 1/1 Running 0 48m

在这种情况下,正确的 sed 命令是什么?

标签: regexbashperlsed

解决方案


有几个问题:

  • .after^需要一个字符
  • (foo-bar)在 POSIX BRE 模式匹配中(foo-bar),但您的字符串中没有括号
  • [^\s]在 POSIX 括号表达式中匹配除\and以外的字符s,而不是非空白字符
  • +在 POSIX BRE 模式中匹配一个+字符。

采用

sed -n 's/^.*\(foo-bar[^[:space:]]*\).*/\1/p'

这里,

  • -n - 禁止默认行输出
  • s- 替换命令
  • /^.*\(foo-bar[^[:space:]]*\).*/ - matches start of the string, any 0+ chars, capturesfoo-bar and 0 or more chars other than whitespace into Group 1 (\1`),然后匹配字符串的其余部分
  • \1 - replaces the whole match with Group 1 contents
  • p - prints the result of the substitution.

Alternatively, consider an awk command that will work if the match is always expected at the start of the string:

awk '$0 ~ /^foo-bar/{print $1}'

See the online demo. It means that if the line starts with foo-bar ($0 ~ /^foo-bar/) awk will print Field 1 (the default field separator is whitespace, so you will get the substring from the start till the first whitespace).


推荐阅读