以下是按预期工作的。我想用“
”替换“我”这个词 echo "test ' this" | sed 's/'"'"'/me/g'
test me this
预期结果:
test \' this
是否可以在同一命令中转义双引号?
答案 0 :(得分:47)
您的问题有点令人困惑,因为要替换的原始字符串中没有me
。但是,我想我拥有它。让我解释一下:
我有一个
sed
命令,可以使用单词'
成功替换单引号me
。我想要一个类似的,可以用字符序列\'
替换它。
如果是这种情况(你只想逃避单引号),你可以使用:
pax$ echo "test ' this" | sed "s/'/\\\'/g"
test \' this
通过在sed
命令周围使用双引号,您无需担心嵌入的单引号。你做然后担心转义,因为shell会吸收一级转义,以便sed
看到:
s/'/\'/g
会根据需要将'
转换为\'
。
如果您想要使用单个sed
同时转义单个和双引号,则最简单的方法是向sed
提供多个命令,以便您可以使用备用引用:
pax$ echo "Single '" 'and double "'
Single ' and double "
pax$ echo "Single '" 'and double "' | sed -e "s/'/\\\'/g" -e 's/"/\\"/g'
Single \' and double \"
如果我误解了你的要求,可以提供一些例子。
答案 1 :(得分:12)
我对你的问题有些怀疑,但无论如何,我的解决方案对任何人都有用。
让我先说一遍:
\\这意味着一个\,因为当你把两个放在一起时,你正在取消它作为元字符的含义。并且\ x27作为单引号,至少对我而言比单个双引号更容易......
最后我把
echo "test me this" | sed 's/me/\\\x27/g'
所以在这里你测试我==>测试这个
echo "test \' this" | sed 's/\\\x27/me/g'
这是相反的。
答案 2 :(得分:7)
这是你的意思吗?:
# cat <<! | sed 's/["'"'"']/\\&/g'
> quote '
> double quotes "
> quote ' double quotes "
> !
quote \'
double quotes \"
quote \' double quotes \"
或者这个:
# echo "test me test"|sed 's/me/\\'"'"'/g'
test \' test
# echo "test me test"|sed 's/me/\\"/g'
test \" test
我发现最好总是在命令行上单引号sed / awk / perl ...命令,并为其中使用的双引号参数制作“漏洞”。
答案 3 :(得分:0)
我需要在脚本中使用'来创建dnsmasq配置文件,这是我使用的技术:
echo -e "\toption name *$name*"|sed s/*/\'/g
示例输出
option name 'GarageDoor'