1

I am trying to add backslash before single and double quote. The problem that I have is that I want to exclude triple quote.

What I did is as for now:

for single quote:

sed -e s/\'/\\\\\'/g test.txt > test1.txt

for double quote:

sed -e s/\"/\\\\\"/g test.txt > test1.txt

I have text like:

1,"""Some text XM'SD12X""","""Some text XM'SD12X""","""Auto " Moto " Some text"Some text"""

What I want is:

120,"""Some text\'SD12X""","""Some text XM\'SD12X""","""Auto \" Moto \" Some text\"Some text"""
marnaels
  • 95
  • 8
  • This might help: [How to add quote at the end of line by SED](https://stackoverflow.com/q/64398822/3776858) – Cyrus Oct 17 '20 at 14:21

1 Answers1

1

If perl is okay:

perl -pe 's/"{3}(*SKIP)(*F)|[\x27"]/\\$&/g'
  • "{3}(*SKIP)(*F) don't change triple double quotes
    • use (\x27{3}|"{3})(*SKIP)(*F) if you shouldn't change triple single/double quotes
  • |[\x27"] match single or double quotes
  • \\$& prefix \ to the matched portion

With sed, you can replace the triple quotes with newline character (since newline character cannot be present in pattern space for default line-by-line usage), then replace the single/double quote characters and then change newline characters back to triple quotes.

# assuming only triple double quotes are present
sed 's/"""/\n/g; s/[\x27"]/\\&/g; s/\n/"""/g'
Sundeep
  • 23,246
  • 2
  • 28
  • 103