Sed Replace ' with \'

This:

echo "Hel'lo" | sed s/\'/\\\'/g

Yields

Hel'lo

What I want is this:

Hel\'lo

What am I missing?

4 Answers

echo "Hel'lo" | sed "s/'/\\\'/g"
Hel\'lo

Also

echo "Hel'lo" |  sed s/\'/\\\\\'/g
1

Or without quoting the sed argument:

echo "Hel'lo" | sed s/\'/\\\\\'/g

You can also do it with all single quotes:

echo "Hel'lo" | sed 's/'\''/\\'\''/g'

And since your question is also tagged bash, I might as well point out that you don't even need sed:

[ghoti@pc ~]$ foo="Hel'lo"
[ghoti@pc ~]$ echo "${foo/\'/\'}"
Hel\'lo

This might work for you:

echo "Hel'lo" | sed 's/'\''/\\&/'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest