Reputation: 453
I am having trouble with expanding variables and ignoring their forward slashes.
I have written a simple script that finds text in my git repository and replaces it with other text. This works fine, but now I want to expand it using regex. This shouldn't be too much of a problem since both git grep and sed support regex. However, when I try to use regex in my input variables the forward slashes are removed which ruins the script.
If I run git grep "\bPoint"
in the terminal I will get many results. However, I can't figure out how to get the same results when I use user input in my script. The git grep
file will change my input to bPoint
instead of \bPoint
, and won't find any results to give to 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"
I've tried a lot of different combinations of quotations, but nothing seems to work for me.
Upvotes: 2
Views: 1777
Reputation: 785128
You must use read -r
. As per help read
:
-r
do not allow backslashes to escape any characters
Examples:
# 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
Upvotes: 3