shell:在反引号中使用 sed

发布于 2024-08-06 17:19:40 字数 506 浏览 6 评论 0原文

我想自动转义字符串中的一些特殊字符。 我想回显该字符串并通过一些 sed 进行管道传输。这似乎在反引号内不起作用。 那么为什么

echo "foo[bar]" | sed 's/\[/\\[/g'

return

foo\[bar]

FOO=`echo "foo[bar]" | sed 's/\[/\\[/g'` && echo $FOO

只是 return 呢

foo[bar]

与 sed 相比,tr 在反引号内完美工作:

FOO=`echo "foo[bar]" | tr '[' '-' ` && echo $FOO

返回

foo-bar]

I want to escape some special chars inside a string automatically.
I thought of echoing that string and pipe it through some seds. This doesn't seem to work inside of backticks.
So why does

echo "foo[bar]" | sed 's/\[/\\[/g'

return

foo\[bar]

but

FOO=`echo "foo[bar]" | sed 's/\[/\\[/g'` && echo $FOO

just returns

foo[bar]

?

In contrast to sed, tr works perfectly inside of backticks:

FOO=`echo "foo[bar]" | tr '[' '-' ` && echo $FOO

returns

foo-bar]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

权谋诡计 2024-08-13 17:19:40

不使用反引号而是使用 $() 怎么样?

FOO=$(echo "foo[bar]" | sed 's/\[/\\[/g') && echo $FOO

如果您坚持使用反引号,我认为您需要将所有 \ 额外转义为双 \

FOO=`echo "foo[bar]" | sed 's/\\[/\\\\[/g'` && echo $FOO

How about not using backticks but use $() ?

FOO=$(echo "foo[bar]" | sed 's/\[/\\[/g') && echo $FOO

if you insist on using backticks, I think you need to extra escape all \ into double \

FOO=`echo "foo[bar]" | sed 's/\\[/\\\\[/g'` && echo $FOO
給妳壹絲溫柔 2024-08-13 17:19:40

您需要转义反引号之间的反斜杠。

FOO=`echo "foo[bar]" | sed 's/\\[/\\\\[/g'` && echo $FOO

或者,使用 $() (这实际上是推荐的方法)。

FOO=$(echo "foo[bar]" | sed 's/\[/\\[/g') && echo $FOO

You need to escape the backslashes between the backticks.

FOO=`echo "foo[bar]" | sed 's/\\[/\\\\[/g'` && echo $FOO

Alternatively, use $() (this is actually the recommended method).

FOO=$(echo "foo[bar]" | sed 's/\[/\\[/g') && echo $FOO
动听の歌 2024-08-13 17:19:40

通常,这是一种逃逸的情况

FOO=`echo "foo[bar]" | sed 's/\[/\\\[/g'` && echo $FOO

Usually, it's a case of underescaping

FOO=`echo "foo[bar]" | sed 's/\[/\\\[/g'` && echo $FOO
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文