BASH:使用sed替换字符串中的组

时间:2021-11-21 16:51:04

Contents contains a string that was read from a file. What I want to do is to replace the capture groups with the groups and a newline character. But I don't know how.

内容包含从文件中读取的字符串。我想要做的是用组和换行符替换捕获组。但我不知道怎么做。

This works

contents=$(echo $contents | sed -e 's|/$(#.*)\n||g')

But this doesn't

但事实并非如此

contents=$(echo $contents | sed -e 's|/$(#.*)\n|\1\n|g')
ERROR: sed: -e expression #1, char 18: invalid reference \1 on `s' command's RHS

And neither does this

这也不是

contents=$(echo $contents | sed -er 's|/$(#.*)\n|\1\n|g')
ERROR: sed: can't read s|/$(#.*)\n|\1\n|g: No such file or directory

1 个解决方案

#1


0  

If content is multiline $content must be between double quotes to avoid splitting: $ has a special meaning in regex it's the end of line anchor, must be escaped. Group parentheses must be escaped (except with -r extended regex). Also \n is not matched $ can be used instead.

如果内容是多行$ content必须在双引号之间以避免拆分:$在正则表达式中具有特殊含义它是行结束锚,必须进行转义。必须对组括号进行转义(使用-r扩展正则表达式除外)。另外\ n不匹配$可以代替使用。

content=$(echo "$content"|sed -e 's|/\$\(#.*\)$|\1|g')

#1


0  

If content is multiline $content must be between double quotes to avoid splitting: $ has a special meaning in regex it's the end of line anchor, must be escaped. Group parentheses must be escaped (except with -r extended regex). Also \n is not matched $ can be used instead.

如果内容是多行$ content必须在双引号之间以避免拆分:$在正则表达式中具有特殊含义它是行结束锚,必须进行转义。必须对组括号进行转义(使用-r扩展正则表达式除外)。另外\ n不匹配$可以代替使用。

content=$(echo "$content"|sed -e 's|/\$\(#.*\)$|\1|g')