停止转义 bash 变量中的正斜杠

Stop escaping forward slash in bash variables

我在扩展变量和忽略它们的正斜杠时遇到问题。

我编写了一个简单的脚本,用于在我的 git 存储库中查找文本并将其替换为其他文本。这工作正常,但现在我想使用正则表达式扩展它。这应该不是什么大问题,因为 git grep 和 sed 都支持正则表达式。但是,当我尝试在我的输入变量中使用正则表达式时,正斜杠被删除,这会破坏脚本。

如果我在终端中 运行 git grep "\bPoint" 我会得到很多结果。但是,当我在脚本中使用用户输入时,我不知道如何获得相同的结果。 git grep 文件会将我的输入更改为 bPoint 而不是 \bPoint,并且不会找到任何要提供给 sed 的结果。

#!/bin/bash

# This script allows you to replace text in the git repository without damaging
# .git files. 

read -p "Text to replace: " toReplace
read -p "Replace with: " replaceWith

git grep -l ${toReplace}

# The command I want to run
#git grep -l "${toReplace}" | xargs sed -i "s,${toReplace},${replaceWith},g" 

我尝试了很多不同的引用组合,但似乎没有任何效果。

您必须使用 read -r。根据 help read:

-r do not allow backslashes to escape any characters

示例:

# without -r
read -p "Text to replace: " toReplace && echo "$toReplace"
Text to replace: \bPoint
bPoint

# with -r
read -rp "Text to replace: " toReplace && echo "$toReplace"
Text to replace: \bPoint
\bPoint