使用 bash 变量时 sed 结果不同

sed results different when using bash variables

测试文件包含以下字符串:

$ cat testfile
x is a \xtest string

以下脚本尝试替换转义序列:\x 出现 yy 使用 sed

#!/bin/bash
echo "Printing directly to stdout"
sed -e "s/\\x/yy/g" testfile
var1=`sed -e "s/\\x/yy/g" testfile`
echo "Printing from variable"
echo "${var1}"

如下图所示,保存到临时变量和不保存到临时变量时打印的结果是不同的。有人可以帮我理解为什么会这样吗? 我希望变量保存仅替换 \x

的字符串
Printing directly to stdout
x is a yytest string
Printing from variable
yy is a \yytest string

平台:macOS

你应该像这样把你的命令放在 $(...) 中:

#!/bin/bash
echo "Printing directly to stdout"
sed -e "s/\\x/yy/g" testfile
var1=$(sed -e "s/\\x/yy/g" testfile)
echo "Printing from variable"
echo "${var1}"