I have a string message which contains data in double quotes. I need to put \ in front of every double quote how can u do it in shell ?

I used Perl and it works fine, but I'm looking for sh command:

cat sampleMetadata | perl -wpe 's/([\\"])/\\$1/g'
  • Your Perl one can be shorter perl -wpe 's/"/\\$&/g'
    – cuonglm
    Commented Jul 27, 2015 at 15:22

2 Answers 2


With standard tools chest, sed is a good one:

sed -e 's/"/\\&/g' <sampleMetadata

Other way to escape double-quotes (and other special simbols) put all line(s) in single qoutes (if it is absent in your text):

sed "s/^\|$/'/g" <sampleMetadata

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .