I have a shell variable which will be used within the replacement string of a sed regex. Therefore, all characters &, / and \ need to be escaped by a preceeding \.

I managed to do it for & and / by

newvar=`echo "$oldvar" | sed -e 's|&|\\\&|g' -e 's|/|\\\/|g'`

1st question: Is this fine (piping content to sed via echo etc.)?

2nd question: Somehow I cannot get it to work for the backslash. Can you show me how to do it?

marked as duplicate by Jeff Schaller, Stéphane Chazelas sed Mar 13 at 13:55

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

Browse other questions tagged or ask your own question.