使用sed提取子字符串报告错误消息

huangapple go评论50阅读模式
英文:

extract substring with sed report error message

问题

我想使用sed提取子字符串,如下所示:

#!/bin/bash
txt="[audio.sys.offload.pstimeout.secs]: [3]"
echo $txt | sed -r -e 's/\[[a-zA-Z0-9_.]+\].*//'

预期输出是:

audio.sys.offload.pstimeout.secs

错误消息:

sed: -e expression #1, char 26: invalid reference  on `s' command's RHS
英文:

I would like to extract substring with sed as below:

#!/bin/bash
txt="[audio.sys.offload.pstimeout.secs]: [3]"
echo $txt|sed -r -e 's/\[[a-zA-Z0-9_.]+\].*//'

expected output is:

audio.sys.offload.pstimeout.secs

Error message:

sed: -e expression #1, char 26: invalid reference  on `s' command's RHS

答案1

得分: 1

#!/bin/bash
txt="[audio.sys.offload.pstimeout.secs]: [3]"
echo $txt | sed -r -e 's/^\[(.*)\]:.*//'

我们捕获从第一个[到最后一个`]:之间的所有字符并将它们放入一个捕获组。

您希望正则表达式基本保持不变吗?

顺便说一下 - 使用懒惰匹配(sed不支持)的话,正则表达式可以更简洁,只需^\[(.*?\])

英文:
#!/bin/bash
txt="[audio.sys.offload.pstimeout.secs]: [3]"
echo $txt | sed -r -e 's/^\[(.*)\]:.*//'

we're grabbing all the characters from the 1st [ until the last ]: and putting them in a capture group.

Would you like the regex to remain mostly like yours?

by the way - with lazy matching (which isn't supported by sed),
the regex could be cleaner, simply ^\[(.*?\])

huangapple
  • 本文由 发表于 2023年2月18日 01:22:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75487416.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定