Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The sed FAQ
Prev Home Next

4.15. How do I prevent regex expansion on substitutions?

Sometimes you want to match regular expression metacharacters as literals (e.g., you want to match "[0-9]" or "\n"), to be replaced with something else. The ordinary way to prevent expanding metacharacters is to prefix them with a backslash. Thus, if "\n" matches a newline, "\\n" will match the two-character string of 'backslash' followed by 'n'.

But doing this repeatedly can become tedious if there are many regexes. The following script will replace alternating strings of literals, where no character is interpreted as a regex metacharacter:

     # filename: sub_quote.sed
     #   author: Paolo Bonzini
     # sed script to add backslash to find/replace metacharacters
     N;                  # add even numbered line to pattern space
     s,[]/\\$*[],\\&,g;  # quote all of [, ], /, \, $, or *
     s,^,s/,;            # prepend "s/" to front of pattern space
     s,$,/,;             # append "/" to end of pattern space
     s,\n,/,;            # change "\n" to "/", making s/from/to/
     #---end of script---

Here's a sample of how sub_quote.sed might be used. This example converts typical sed regexes to perl-style regexes. The input file consists of 10 lines:

       [0-9]
       \d
       [^0-9]
       \D
       \+
       +
       \?
       ?
       \|
       |

Run the command "sed -f sub_quote.sed input", to transform the input file (above) to 5 lines of output:

       s/\[0-9\]/\\d/
       s/\[^0-9\]/\\D/
       s/\\+/+/
       s/\\?/?/
       s/\\|/|/

The above file is itself a sed script, which can then be used to modify other files.

The sed FAQ
Prev Home Next

 
 
   Reprinted courtesy of Eric Pement. Also available at https://sed.sourceforge.net/sedfaq.html Design by Interspire