英文:
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 ^\[(.*?\])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论