0

I want to replace

headers['Content-Disposition'] = "attachment; filename=%s" % (filename)

with

headers['Content-Disposition'] = 'attachment; filename="%s"' % (filename)

(so that the "%s" is double-quoted).

My best effort so far is

sed -i -e 's/"headers[\'Content-Disposition\'] = \"attachment\; filename=%s\" % \(filename\)"/"headers[\'Content-Disposition\'] = \'attachment\; filename=\"%s\"\' % \(filename\)"/g' test.txt

but it fails:

sed: -e expression #1, char 33: unterminated `s' command

I tried all that I could come across on stackoverflow and elsewhere. I tried escaping the quotes as well. But this too much of single and double quotes is causing errors.

I have scanned the line and I'm sure I haven't left any unterminated quotes. How can I get it working?

  • 1
    sed -e "s/\"/'/g" -e 's/%s/"%s"/' ? – grochmal Oct 7 '16 at 2:44
  • thanks. but the result was little different. expected output headers['Content-Disposition'] = 'attachment; filename="%s"' % (filename) whereas what you suggested produces the following: headers['Content-Disposition'] = 'attachment; filename='"%s"'' % (filename) – Selva Prasad Oct 7 '16 at 4:21
0

Try this:

sed -i -e "s/headers\['Content-Disposition'\] = \"attachment; filename=%s\" % (filename)/headers\['Content-Disposition'\] = 'attachment; filename=\"%s\"' % (filename)/g" test.txt
1

You can avoid "'quoting hell'" by putting your sed commands into a file. Then they are not subject to Bash quoting, and you only have to worry about what's significant to sed:

#!/bin/sed -f

# Adjust this to match as much as you need
/headers\['Content-Disposition'\] = /{

# change all double-quotes to single
y/"/'/
# now double-quote the %s argument
s/%s/"&"/g

}
  • +1 for mentioning sed -f, that is the right way to deal with levels of quoting. – grochmal Oct 7 '16 at 10:05
0

Assuming input is a file that holds the data:

sed "y/\"/'/;s/%s/\"&\"/" input
  • thanks agc. but the result was little different. expected output headers['Content-Disposition'] = 'attachment; filename="%s"' % (filename) whereas what you suggested produces the following: headers['Content-Disposition'] = 'attachment; filename='"%s"'' % (filename) – Selva Prasad Oct 7 '16 at 4:23
0

Although there already is an accepted answer, here is another (a little shorter) variant:

sed -r "s/\"([a-z])/'\1/; s/([a-z])\"/\1'/; s/=([^[:space:]]{2})/\"\1\"/" headers 
headers['Content-Disposition'] = 'attachment; filename"%s"' % (filename)

You could probably make it even more terse, but I choose to split the sed into three distinct parts to make it at least slightly more readable!


sed --version
sed (GNU sed) 4.2.2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.