Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Inserting bash script variable into regex string

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading