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:
- 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.
- When your path gets expanded, the character (i.e.
/) you’re using to delimit the substitution expressions collides with it. - Your
sedcommand seems to not work on my Mac OS X and this may be because it differs betweengsedand the Mac version.
Here’s the corrected expression using # as the delimiting character:
sed -i -e "s#path=\".*\"#path=\"${userPath}\"#g" hello.txt