Inserting bash script variable into regex string

Issue

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

Solution

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

Answered By – CinchBlue

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published