51

I would like to replace $fileWithPath in $file, however this doesn't work because (I think) path is not escaped. How to escape it?

sed -i 's/${fileWithPath}/HAHA/g' $file
0

3 Answers 3

87
sed -i 's|'$fileWithPath'|HAHA|g' file

Single quotes define a string literal. Putting the variable outside the literal allows the shell to expand that part.

Also: if you are going to parse paths, use a delimiter in the sed command that doesn't confuse with the directory delimiter "/".

4
  • 1
    Beware that if $fileWithPath contains whitespace, the wrong pattern is inserted.
    – Lekensteyn
    Nov 7, 2011 at 18:09
  • Your bonus tip about changing the delimiter for file paths was a life saver!
    – Shadoninja
    May 11, 2016 at 23:55
  • I think you have too much quotes in your command. My example sed -i 's|auth-user-pass nordvpn.txt|auth-user-pass /etc/openvpn/nordvpn.txt|g' *.ovpn seems to work. Mar 5, 2017 at 20:56
  • @LéoLéopoldHertz it will work as long as you don't need to expand a variable. My example used a variable so I had to use two single quotes sections (otherwise the variable wouldn't exapand). An option is to use double quotes instead, but that adds other effects to the sed string.
    – ata
    Apr 6, 2020 at 15:05
23

A better way for literal strings with forward slashes:

sed -i "s|my/path|my/other/path|g" myFileOfPaths.txt
1
  • This one deserved an Oscar! Simple and elegant Nov 8, 2019 at 8:42
14

In circumstances where the replacement string or pattern string contain slashes, you can make use of the fact that GNU sed allows an alternative delimiter for the substitute command. Common choices for the delimiter are the pipe character | or the hash # - the best choice of delimiting character will often depend on the type of file being processed. In your case you can try

sed -i 's#'$fileWithPath'#HAHA#g' $file

The character 'g' after last # is used to change all occurrences in file if you need to change only first occurrence then remove the 'g'.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .