Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replacing double quotes with backslash and double quotes [duplicate]

Tags:

bash

tr

I am trying to replace a double quotes (") with back slash and double quotes (") however it's not working

echo '"hello workd"' | tr '"' '\\""'

This gives me

\hello workd\

and following does nothing.

echo '"hello workd"' | tr '"' '\"'
like image 563
Gaurang Shah Avatar asked Dec 30 '25 09:12

Gaurang Shah


1 Answers

tr is not the right tool for this as it replaces one character with another. You may use sed like this:

echo '"hello workd"' | sed -E 's/"/\\&/g'

\"hello workd\"

In s/"/\\&/g we are matching a " and replacing with a \ followed by the full match i.e. " itself.

like image 58
anubhava Avatar answered Jan 01 '26 03:01

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!