Escape single quote

Your question is a little confusing since there’s no me in the original string to replace. However, I think I have it. Let me paraphrase:

I have a sed command which can successfully replace a single quote ' with the word me. I want a similar one which can replace it with the character sequence \'.

If that’s the case (you just want to escape single quotes), you can use:

pax$ echo "test ' this" | sed "s/'/\\\'/g"
test \' this

By using double quotes around the sed command, you remove the need to worry about embedded single quotes. You do have to then worry about escaping since the shell will absorb one level of escapes so that sed will see:

s/'/\'/g

which will convert ' into \' as desired.

If you want a way to escape both single and double quotes with a single sed, it’s probably easiest to provide multiple commands to sed so you can use the alternate quotes:

pax$ echo "Single '" 'and double "'
Single ' and double "

pax$ echo "Single '" 'and double "' | sed -e "s/'/\\\'/g" -e 's/"/\\"/g'
Single \' and double \"

If I’ve misunderstood your requirements, a few examples might help.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)