Use Sed to Replace a Specific String with Slashes

I have a big text file -a windows registry file- about 5.5MB and I have to remove a string "serv\b\Param\". Opening with gedit or nano doesn't work. It will either consume 100% cpu time for some unreasonable long amount of time or it will just print random garbage of text. I tried using these commands from linux because I can't use the other one:

sed -i 's|"serv\b\Param"|""|g' ~/Desktop/3.reg

sed -i 's|\"serv\b\Param"|\""|g' ~/Desktop/3.reg

sed -i 's:serv\b\Param:"":g' ~/Desktop/3.reg

sed -i 's:serv\b\Param::g' ~/Desktop/3.reg

sed -i 's:"serv\b\Param":"":g' ~/Desktop/3.reg

Nothing work so far. What is wrong with these commands?

2

2 Answers

The slashes need to be escaped:

sed -i 's|serv\\b\\Param\\||g' ~/Desktop/3.reg

In sed, a single backslash is usually a escape character for something. For example, in GNU sed, an escape-b, as in \b, is interpreted to mean a word boundary. To prevent such interpretation, place two backslashes in a row where ever you want to match a single literal backslash.

Example

Based on your sample (updated as per the comments), let's start with this file:

$ cat 3.reg
serv\b\Param\
abc serv\b\Param\ def

Applying the above sed command:

$ sed -i 's|serv\\b\\Param\\||g' 3.reg
$ cat 3.reg

abc  def

The pattern is successfully removed.

The basic problem is that \ introduces various sequences in regular expressions, so to match \ in the input stream you need to use \\ in the RE.

It is not clear whether the quotes are part of the string you want to remove: from your fourth example I would assume not, in which case this example works if you double the back-slashes:

sed -i 's:serv\\b\\Param::g' ~/Desktop/3.reg

You do not need double-quotes in the search or replacement strings unless they form part of the search criteria: the single-quotes around the edit expression already remove any special meanings as far as the shell is concerned, so sed sees the literal expression.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest