sed Shennanigans…

Escaping…

For anyone familiar with regular expressions, the need to escape characters, that might otherwise be construed as some “special command”, is a regular affair…

sed posed a particular challenge for me when attempting to escape variables that are used as a replacement string. So, to cut the long story short, after 8 hours of trying, testing and re-testing, I finally got the solution…

In a bash shell, try the following:

TESTSTRING='\/12345678\90!@#$%^&*()-_=+{}[];:",.<>? `~abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
sed "s#\([^[:alnum:]]\)#\\\\\1#g"<<<$TEST

Otherwise, in a script, try the following:

TESTSTRING='\/12345678\90!@#$%^&*()-_=+{}[];:",.<>? `~abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
TESTSTRING=`echo $TESTSTRING|sed 's#\([^[:alnum:]]\)#\\\\\1#g'

WARNING: This does not work with intended backreferences (e.g. \1, \2, … \9, etc.) as the leading backslash will also be escaped (see the \9 in the tests above).

NOTE: The single-quote character was not part of the tests as I could not find a way to escape that as part of the variable assignment.

Leave a Reply