如何使用sed用反引号替换字符串

How to use sed to replace string with backtick

我如何使用 shell/bash 脚本的 'sed',用变量的内容替换字符串并用 acute/backslash 包围它。

例如:

文件(file.txt)包含行

FILE_PATH="this/is/the/file/path" 

一样被替换
FILE_PATH=`get/file/path/get.sh FILE_NAM`

我尝试了以下 sed,但对我不起作用

SCRIPT_PATH="get/file/path/get.sh FILE_NAM"
sed -i "s,\"this/is/the/file/path\",`$SCRIPT_PATH`,g" $file

以上结果

FILE_PATH=get/file/path/

但预期是

FILE_PATH=`get/file/path/get.sh FILE_NAM`

有人可以帮我用变量的内容替换字符串,acure 围绕变量的值。

如果问题完全出在 sed,您的命令格式不正确。看起来总体问题是您没有打印 ` 字符的转义序列,这是 bash 中的一个特殊字符,用于在另一个命令中执行 shell 命令。

根据您想要的结果和示例代码,以下内容适用于 bash。

SCRIPT_PATH="this/is/the/file/path"
sed -i "s|\"this/is/the/file/path\"|\`$SCRIPT_PATH\`|g" file.txt

我找到的答案如下:

SCRIPT_PATH="get/file/path/get.sh FILE_NAM"
sed -i "s,\"this/is/the/file/path\","\`"$SCRIPT_PATH"\`",g" $file