外壳:在反引号中使用sed [英] shell: Using sed in backticks

查看:263
本文介绍了外壳:在反引号中使用sed的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想自动在字符串中转义一些特殊字符。
我想到了回显该字符串并将其通过一些sed传递的方法。这似乎在反引号内不起作用。
那么为什么

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'

返回

foo\[bar]

但是

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

只是返回

foo[bar]

与sed相比,tr可以在反引号内完美运行:

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

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

返回

foo-bar]


推荐答案

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

这篇关于外壳:在反引号中使用sed的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆