【问题标题】:Stop escaping forward slash in bash variables停止在 bash 变量中转义正斜杠
【发布时间】:2016-03-24 19:03:34
【问题描述】:

我无法扩展变量并忽略它们的正斜杠。

我编写了一个简单的脚本,可以在我的 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" 

我尝试了很多不同的引用组合,但似乎没有什么对我有用。

【问题讨论】:

  • 这不是正斜杠,而是反斜杠。

标签: regex bash grep escaping user-input


【解决方案1】:

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

-r 不允许反斜杠转义任何字符

示例:

# 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

【讨论】:

  • 做到了。谢谢!
  • 另外,在变量引用周围使用双引号(例如git grep -l "${toReplace}")以避免意外的分词和/或通配符扩展。
猜你喜欢
  • 2012-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-07
  • 2016-10-28
  • 2021-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多