如何在sed中插入包含反斜杠的变量? [英] How can I insert a variable containing a backslash in sed?
问题描述
请查看以下简单命令:
$ echo $tmp
UY\U[_
$ echo "a" | sed "s|a|${tmp}|g"
UY[_
\U
被吃掉了.其他反斜杠也将无法生存.
The \U
is eaten. Other backslashes won't survive either.
如何使上述命令按预期工作?
How can I make the above command work as expected?
推荐答案
如果只有sed被吃"了反斜杠并转义就足够了,请尝试:
If it's only backslash that is "eaten" by sed and escaping just that is enough, then try:
echo "a" | sed "s|a|${tmp//\\/\\\\}|g"
让您感到困惑吗? \\
表示单个\,因为它也需要在外壳中转义.
初始//
类似于s/foo/bar/g
中的g
修饰符,如果您只想替换第一个出现的模式,请跳过它.
Confusing enough for you? \\
represents a single \ since it needs to be escaped in the shell too.
The inital //
is similar to the g
modifier in s/foo/bar/g
, if you only want the first occurring pattern to be replaced, skip it.
有关${parameter/pattern/string}
的文档位于此处: http://www.gnu.org/s/bash/manual/bash.html#Shell-Parameter-Expansion
The docs about ${parameter/pattern/string}
is available here: http://www.gnu.org/s/bash/manual/bash.html#Shell-Parameter-Expansion
编辑:根据您要执行的操作,最好不为此实际使用sed.
Depending on what you want to do, you might be better of not using sed for this actually.
$ tmp="UY\U[_"
$ in="a"
$ echo ${in//a/$tmp}
UY\U[_
这篇关于如何在sed中插入包含反斜杠的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!