Home > OS >  Inserting bash script variable into regex string
Inserting bash script variable into regex string

Time:07-21

I'm trying to run a sed command in a bash script I have which replaces a string between two quotation marks from another file with another string.

The file I'm editing:

path="text"

Bash script:

userPath=$(pwd)
sed -i 's/path=".*"/path="${userPath}"/g' file

but after running the script, my file gets edited as this instead of the actual path that gets outputted from the pwd (etc. path="/home/Downloads") command:

path="${userPath}"

I tried replacing the single quotes on the outside to double quotes, but I got some "unknown option to 's'" error when running the script. Attempting to add extra quotes and escape them like below did not work either.

sed -i 's/path=".*"/path="\"${userPath}\""/g' file

CodePudding user response:

You have 3 problems:

  1. You are using single-quotes which means the Bash substitutions do not get expanded within the string -- you need to use double-quotes and escape your in-string double-quotes.
  2. When your path gets expanded, the character (i.e. /) you're using to delimit the substitution expressions collides with it.
  3. Your sed command seems to not work on my Mac OS X and this may be because it differs between gsed and the Mac version.

Here's the corrected expression using # as the delimiting character:

sed -i -e "s#path=\".*\"#path=\"${userPath}\"#g" hello.txt

CodePudding user response:

There are a few issues with your command

  • You need double quotes for the variable to expand
  • As a result of the double quotes, you would need to escape the double quotes within the command
  • The variable contains the forward slash / character which will conflict with seds default delimiter.

For your code to work, you would need to change it to;

$ sed -Ei.bak "s~path=\".*\"~path=\"${userPath}\"~g" file

-i.bak will create a backup of the file

  • Related