使用sed替换正则表达式和包含数字的变量

时间:2018-09-19 18:47:40

标签: sed

我在弄清sed行的语法时遇到问题。我使用正则表达式,因此在整个过程中都使用了双引号。但是,我要替换的Windows路径中有一个数字。

windowsPath="\\\\This\\path\\is\\the\\best\\1"
sed -i "s,^bestPath=.*,bestPath=${windowsPath}," pathfile

这给了我

sed: -e expression #1, char 126: invalid reference \1 on `s' command's RHS

我试图将变量保留在引号内以避免解释,但是后来我明白了:

代码:

windowsPath="\\\\This\\path\\is\\the\\best\\1"
sed -i "s,^bestPath=.*,bestPath="${windowsPath}"," pathfile

结果:

sed: -e expression #1, char 42: unterminated `s' command

任何sed大师对这里发生的事情有想法吗?我正在RHEL 6上进行bash工作

1 个答案:

答案 0 :(得分:1)

在WindowsPath分配中,使用单引号(')而不是双引号(“)。

#!/bin/bash

windowsPath='\\\\This\\path\\is\\the\\best\\1'
sed -e "s,^bestPath=.*,bestPath=${windowsPath}," pathfile

exit $?

输出为

bestPath=\\This\path\is\the\best\1

希望这会有所帮助