Ubuntu – Sed search and replace with variable containing slash

bashcommand linesed

I am trying to replace a string inside a text file with a variable.

I am using this code:

sed -i "s/search text \/TAG\//replace text ${variable}/" ${textfile}

The content of the variable is /newTAG/. And the content of the variable is the problem, more accuratelyte the / at the beginning and the end.

When both / are removed so the content is only newTAG everything works fine.

I already tried the following

sed -i "s/search text \/TAG\//replace text "${variable}"/" ${textfile}
sed -i 's/search text \/TAG\//replace text "${variable}"/' ${textfile}

Can anybody help me?

Best Answer

  • Use something other than / as the delimiter for the regex (for example, the colon :):

    sed -i "s:search text /TAG/:replace text ${variable}:" "${textfile}"

    Or escape the / in the variable.

  • Related Question