Substitution when special charcters involved

I am trying to substitute a substring in a file and am having difficulty due to the presence of 'special characters'

I tried

sed -e "s/Bob's birthday 13/11/08 (today)/Bob's birthday 14/11/08 (tomorrow)/" file1

This does not action any change due to the square brackets.

How can I cater for special characters when making a substitution such as this?

Your help is much appreciated.

Escape the special characters with a backslash:

echo "Bob's birthday 13/11/08 (today)"|\
sed 's/13\/11\/08 (today)/14\/11\/08 (tomorrow)/'
Bob's birthday 14/11/08 (tomorrow)

Thanks for the above, however what if both strings are variables (i.e $string1 and $string2).

Then you will have to do it in the variables contents. You could write a library function (make_regexp()) out of it, which gets a string and escapes it properly:

function pMakeRegexp
{
if [ $# -ne 1 ] ; then
     return 1
fi

# add to the characters in the bracket if i have overlooked one
print - "$1" | sed 's/[/\&^*.$]/\\&/g'

return 0
}

# main
typeset var="some \ special ^ characters / are & here"
typeset regex_var="$(pMakeRegexp "$var")"

print - "var is \"$var\" // regexed var is \"$regex_var\""
print - "xx $var xx" | sed "s/$regex_var/=&=/"

exit 0

As you can see the regexed version "$regex_var" matches normal version "$var" and the replacement (adding the equal signs before and after) is taking place. Similarily you can put the replacement string through pMakeRegexp() too.

I hope this helps.

bakunin

Or use them like this:

VAR1="13\/11\/08 (today)"
VAR2="14\/11\/08 (tomorrow)"

echo "Bob's birthday 13/11/08 (today)"|\
sed "s/${VAR1}/${VAR2}/"
Bob's birthday 14/11/08 (tomorrow)

With sed you can use any character as the pattern separator, e.g. you can replace / with |

sed -e "s|Bob's birthday 13/11/08 (today)|Bob's birthday 14/11/08 (tomorrow)|" file1

See e.g.
http://www.unix.com/shell-programming-scripting/84231-escape-character-sed.html\#post302244111