我需要将 FileA 上出现的“badfile 'C:users\username\desktop”替换为“badfile 'filepath\badfile”。换句话说,将 badfile 'C:users\username\desktop 替换为 badfile 'filepath\badfile
我尝试了以下方法,但没有效果
test=badfile 'C:users\\username\\desktop
test1=badfile 'filepath\\badfile
echo $test
echo $test1
sed -i 's|$test|$test1|g' FileA
我需要有关如何使此代码工作的帮助,或者更好的方法将不胜感激。
最佳答案
您需要:
- 用双引号
"
封装变量的值,以保留其值中的单引号字符。 - 转义反斜杠字符
\
,如\\
- 将
sed
命令中的单引号'
替换为双引号"
,以允许变量替换。使用单引号,您可以告诉它用 字符串$test1
替换 字符串$test
。
你得到:
test="badfile 'C:users\\\\username\\\\desktop"
test1="badfile 'filepath\\\\badfile"
echo $test
echo $test1
sed -i "s|$test|$test1|g" FileA
关于linux - 在linux中用\替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21711223/