sed search and replace with variable containing slash

7,977

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.

Share:
7,977

Related videos on Youtube

Bird Person
Author by

Bird Person

Updated on September 18, 2022

Comments

  • Bird Person
    Bird Person over 1 year

    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? Thanks