gpt4 book ai didi

sed - 转义单引号

转载 作者:行者123 更新时间:2023-12-03 09:02:03 38 4
gpt4 key购买 nike

以下工作正常。我想将“我”一词替换为\'

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

预期结果:
test \' this

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

最佳答案

您的问题有点令人困惑,因为原始字符串中没有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 \'.



如果是这种情况(您只想转义单引号),则可以使用:
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 \"

如果我误解了您的要求,那么一些示例可能会有所帮助。

关于sed - 转义单引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7990750/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com