【问题标题】:sed results different when using bash variables使用 bash 变量时 sed 结果不同
【发布时间】:2022-01-13 16:09:44
【问题描述】:

一个测试文件有以下字符串:

$ 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

【问题讨论】:

  • 与问题无关:您通常应该将 sed 表达式放在单引号而不是双引号中。那么你就不需要加倍反斜杠了。
  • 出现这种情况的原因是因为反引号进程反斜杠转义。
  • @Barmar 我明白了。在所有命令评估中使用$() 而不是反引号会更好吗?或者是否存在反引号优于 $() 的情况?
  • 其他人已经回答了。

标签: bash shell sed


【解决方案1】:

你应该把你的命令放在$(...) 里面:

#!/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}"

【讨论】:

  • 你应该解释为什么这会有所作为。
猜你喜欢
  • 2011-12-02
  • 2021-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-10
  • 1970-01-01
相关资源
最近更新 更多