Sed usage to replace a string having forward slash

Hiya,

I am trying to use sed to replace a string with another in a file but having issue when there is special character.

sed "s/ALERT_MESSAGE/Test/" file.txt

This works fine but how to escape the forward slash in below example

sed "s/ALERT_MESSAGE/<Test> </Test>/" file.txt

Thanks,

@Nick

as you haven't shown and data, here's an example.
the separator does not need to be a / for sed !, so we use # in this example

cat nick.txt 
ALERT_MESSAGE plus some other stuff
plus some other stuff
and an ALERT_MESSAGE down here

sed "s#ALERT_MESSAGE#<Test> </Test>#" nick.txt 
<Test> </Test> plus some other stuff
plus some other stuff
and an <Test> </Test> down here

NB:the same can be achieved by escaping the /, thus

sed "s/ALERT_MESSAGE/<Test> <\/Test>/" nick.txt
2 Likes

Please find more details with file and examples:

Hiya,

I am trying to use sed to replace a string with another in a file but having issue when there is special character.

Sample File : file.txt
Hello, This is a Sample test message. This contains ALERT_MESSAGE.

sed "s/ALERT_MESSAGE/Test/" file.txt

Output -

Hello, This is a Sample test message. This contains Test.

This works fine and String "ALERT_MESSAGE" is replace with Test but how to escape the forward slash in below example

Sample Example :

sed "s/ALERT_MESSAGE/<Test> </Test>/" file.txt

Expected Output :

Hello, This is a Sample test message. This contains <Test> </Test>.

Sample Example :

sed "s/ALERT_MESSAGE/<Test> </Test><Test1> </Test1><Test> </Test>/" file.txt

Expected Output :

Hello, This is a Sample test message. This contains <Test> </Test><Test1> </Test1><Test> </Test>.

String replacing the ALERT_MESSAGE is not known and is received as part of some other functionality so this may have any number of entries with forward slashes.

Thanks,

@Nick , did you read the initial response ?

cat file.txt 
Hello, This is a Sample test message. This contains ALERT_MESSAGE

sed "s#ALERT_MESSAGE#<Test> </Test><Test1> </Test1><Test> </Test>#" file.txt 
Hello, This is a Sample test message. This contains <Test> </Test><Test1> </Test1><Test> </Test>

am i missing something here ?

NB: for EVERY substitution you show, provide the following (as per my example)

  • cat the input file to show the contents in the before state
  • run the command and show the output

nothing inbetween - no commentary - the execution of the commands and subsequent results is all that is required, if, for any reason that requires further information/qualification/elaboration then we will ask.