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...
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 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.