如何在使用 sed 时转义 & 字符 [英] How to escape the ampersand character while using sed

查看:172
本文介绍了如何在使用 sed 时转义 & 字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 sed 用两个单引号替换字符串中的所有单引号.但是当字符串包含 & 字符时,sed 命令不会替换后面的单引号.如何转义 & 字符,以便仍然替换其后的单引号?

I want to replace all single quotes in a string with two single quotes using sed. But when the string contains the & character, the sed command is not replacing single quotes that come after that. How can I escape the & character so that the single quotes after it are still replaced?

推荐答案

输入中的任何内容:

$ echo "123 ' foo & b'ar" | sed "s/'/''/g"
123 '' foo & b''ar

然而,在 s 命令的替换"部分,& 有一个特殊的含义:它的意思是匹配".这就是为什么上面的命令可以重写为:

However, in the 'replacement' part of the s command & has a special meaning: it means 'match'. That's why the above command can be re-written as:

$ echo "123 ' foo & b'ar" | sed "s/'/&&/g"
123 '' foo & b''ar

使用 \ 转义它,就像其他需要转义的东西一样,如果需要:

Escape it with a \ like everything else that needs to be escaped, if needed:

$ echo "123 ' foo & b'ar" | sed "s/'/'\&'/g"
123 '&' foo & b'&'ar

这篇关于如何在使用 sed 时转义 & 字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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