Linux – use sed to replace a specific string with slashes

linuxsed

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?

Best Answer

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.

Related Question