2

I am struggling to replace a string with a special character. I am using the command below and I tried to escape each special character, but I am still getting an error.

If I don't use special characters, the query is working fine, but I have to use special characters.

String to find: ../../../profileone String to Replace: @mysettings/future-system-one

Query:

sed -i s/"../../../profileone"/"@mysettings/future-system-one"/g *.fileExtension'

I wanted to try this command from jenkins pipeline.

terdon
  • 98,183
  • 15
  • 197
  • 293
L V Prasad
  • 23
  • 4
  • 1
    The issue is that your pattern and replacement contain the forward slash, which is also used as the default regex separator. Although you *can* make it work by backslash-escaping the forward slashes, it's simpler IMHO to change the separator. See for example [How to sed and replace string with a folder path](https://askubuntu.com/questions/408960/how-to-sed-and-replace-string-with-a-folder-path) – steeldriver May 22 '21 at 11:47
  • ...and a single quote at the end? –  May 22 '21 at 13:43

2 Answers2

2

Following the comment by @steeldriver, you can change the pattern delimiters from / to _:

sed -i s_"../../../profileone"_"@mysettings/future-system-one"_g *.fileExtension'

so that you don't need to escape all the / in this way:

sed -i s/"..\/..\/..\/profileone"/"@mysettings\/future-system-one"/g *.fileExtension'
mattb
  • 304
  • 1
  • 10
  • Thank you, terdon and mattb below two commands saved me: sed 's|"../../../profileone"|"@mysettings/future-system-one"|g' *.fileExtension sed -i s_"../../../profileone"_"@mysettings/future-system-one"_g *.fileExtension – L V Prasad May 22 '21 at 15:26
2

You don't actually have any special characters there, so you don't need to escape anything. The only issue is that you are using / as the pattern delimiter, so just use another character and it should work fine:

sed 's|../../../profileone|@mysettings/future-system-one|g' *.fileExtension

Note how the sed command is quoted, that is important.

Now, your question shows the target strings as ../../../profileone and @mysettings/future-system-one, but your command also includes double quotes. If those are supposed to be part of the strings, use this instead:

sed 's|"../../../profileone"|"@mysettings/future-system-one"|g' *.fileExtension
terdon
  • 98,183
  • 15
  • 197
  • 293