regex - 正确的 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 命令是什么?
解决方案
有几个问题:
.
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, captures
foo-barand 0 or more chars other than whitespace into Group 1 (
\1`),然后匹配字符串的其余部分\1
- replaces the whole match with Group 1 contentsp
- 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).
推荐阅读
- github - 用于 github 组织的不和谐 webhook
- python - 使用 Ppython 启动已安装的程序
- node.js - 在 Heroku 上运行几个 node.js 脚本
- c++ - 如何在 C++(Arduino/C++)中将字符串转换为 uint8_t?
- javascript - 向 D3js 圆环图添加边框半径属性
- sas - 创建一个宏以根据 SAS 中的日期将月度数据子集为较小的数据集
- mips - 带有尾随 0 的 64 位数字的 MIPS 二进制补码转换
- android - 如何在两个片段之间共享 onTouch MotionEvent?
- python - 没有名为 yum 的模块
- javascript - 更新:突变接收商店,而不是状态