The following is working as expected. I want to replace the word "me" with \'
echo "test ' this" | sed 's/'"'"'/me/g' test me this
Expected result:
test \' this
Is it possible to escape double quotes as well in the same command?
Single quotes need to be escaped by backslash in single-quoted strings, and double quotes in double-quoted strings.
' End first quotation which uses single quotes. " Start second quotation, using double-quotes. ' Quoted character. " End second quotation, using double-quotes.
You need to escape single quote when the literal is enclosed in single code using the backslash(\) or need to escape double quotes when the literal is enclosed in a double code using a backslash(\).
A single quote is not used where there is already a quoted string. So you can overcome this issue by using a backslash following the single quote. Here the backslash and a quote are used in the “don't” word. The whole string is accompanied by the '$' sign at the start of the declaration of the variable.
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 wordme
. 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.
I have some doubts about your question, but anyway maybe my solution is useful for anyone.
Let's me say before all :
\\ that's mean one \ because when you put two together you are cancelling its meaning as metacharacter. And \x27 as single quote, at least for me is easier than working with single a double ...
Finally I put
echo "test me this" | sed 's/me/\\\x27/g'
so here you have test me ==> test \' this
echo "test \' this" | sed 's/\\\x27/me/g'
and here is the opposite.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With