linux - 在linux中用\替换字符串

标签 linux shell sed

我需要将 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

我需要有关如何使此代码工作的帮助,或者更好的方法将不胜感激。

最佳答案

您需要:

  1. 用双引号"封装变量的值,以保留其值中的单引号字符。
  2. 转义反斜杠字符\,如\\
  3. 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/

相关文章:

linux - 用 SED 替换占位符

bash - sed 将 tex 速记 $$ 替换为 latex 速记\(\)

linux - 前台作业和后台作业的区别

python - 之间的差异。 venv/bin/activate 和 ./venv/bin/activate

linux - 包含括号的 awk 协进程的转义序列

regex - 使用 bash 更正文件编号

linux - 使用 awk 命令匹配多个模式

linux - 每隔几秒运行一个脚本

linux - Nagios - 连接被拒绝和套接字超时

shell - 我可以在 unix 脚本中调用 ssh 中的函数吗