linux - 为什么我无法在 sed 替换中转义单引号但使用\x27 有效?

标签 linux bash shell unix sed

我正在尝试用 4 个单引号替换某些内容,但出于某种我不知道的原因转义不起作用!

这是我不工作的命令:

sed -r 's/\*\*(.*)\*\*/\'\'\1\'\'/' file

我不知道为什么它会输出错误,即使我转义了引号。

我知道我可以使用双引号解决问题,例如:

sed -r "s/\*\*(.*)\*\*/\'\'\1\'\'/"

或:

sed -r 's/\*\*(.*)\*\*/\x27\x27\1\x27\x27/'

但是是的,我只想知道第一种形式不起作用的原因。谢谢

最佳答案

首先,我认为使用 \x27 是正确且最易读的方法。

关于你的问题,问题与bash的单引号字符串有关。您不能在单引号字符串中转义单引号。来自bash manual :

3.1.2.2 Single Quotes

Enclosing characters in single quotes (‘'’) preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.

意思是这有效:

echo 'ab\'c'

您需要结束引号字符串,添加转义引号并再次开始单引号字符串:

echo 'ab'\''c'

关于linux - 为什么我无法在 sed 替换中转义单引号但使用\x27 有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46047806/

相关文章:

c++ - 实现 TCP 应用程序内置 shell 的简单方法

c - linux 查找调用的命令

c++ - 带有 ax_check_compile_flag 的 autotools 语法错误

python - 尝试使用 pip3 安装 virtualenvwrapper

Linux Bash Number Range echo 语法错误

linux - Azure VM Linux Ubuntu 备份代理 - 部署失败

linux - 手动密码保护文件/文件夹 (Linux)

linux - Apache 如何访问 root 用户创建的 SSL 证书?

bash - std::process:Command 在使用 'bash -c' 时不返回 Err() 结果

linux - 如果服务器重新启动,如何使 couchbase 服务自动启动?