转义单引号 [英] Escape single quote

查看:99
本文介绍了转义单引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下按预期工作.我想用 \'

The following is working as expected. I want to replace the word "me" with \'

 echo "test ' this" | sed 's/'"'"'/me/g'
test me this

预期结果:

test \' this

是否可以在同一命令中转义双引号?

Is it possible to escape double quotes as well in the same command?

推荐答案

您的问题有点令人困惑,因为原始字符串中没有要替换的 me.不过,我觉得我有.让我解释一下:

Your question is a little confusing since there's no me in the original string to replace. However, I think I have it. Let me paraphrase:

我有一个 sed 命令,它可以成功地用单词 me 替换单引号 '.我想要一个类似的,可以用字符序列 \' 替换它.

I have a sed command which can successfully replace a single quote ' with the word me. I want a similar one which can replace it with the character sequence \'.

如果是这种情况(您只想转义单引号),您可以使用:

If that's the case (you just want to escape single quotes), you can use:

pax$ echo "test ' this" | sed "s/'/\\\'/g"
test \' this

通过在 sed 命令周围使用双引号,您无需担心嵌入的单引号.你确实必须担心转义,因为shell会吸收一层转义,这样sed就会看到:

By using double quotes around the sed command, you remove the need to worry about embedded single quotes. You do have to then worry about escaping since the shell will absorb one level of escapes so that sed will see:

s/'/\'/g

它将根据需要将 ' 转换为 \'.

which will convert ' into \' as desired.

如果你想用一个 sed 来同时转义单双引号,向 sed 提供多个命令可能是最简单的所以你可以使用备用引号:

If you want a way to escape both single and double quotes with a single sed, it's probably easiest to provide multiple commands to sed so you can use the alternate quotes:

pax$ echo "Single '" 'and double "'
Single ' and double "

pax$ echo "Single '" 'and double "' | sed -e "s/'/\\\'/g" -e 's/"/\\"/g'
Single \' and double \"

如果我误解了您的要求,举几个例子可能会有所帮助.

If I've misunderstood your requirements, a few examples might help.

这篇关于转义单引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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