1

I have a string like this:

'abc','D'art','abc'

Using sed I can replace D'a for 'D\'a' using:

sed -i "s/D'a/D\\\'a/g" file1.sql

The problem is that I have a huge SQL file, and every step of the way I have a new combination (D'A, T'b, P'a...)... So I am looking for an effective way of detecting single quotes in between letters so I can escape them.

Any Idea?

1 Answer 1

1

In practice you may want to escape every single-quote adjacent to not-a-comma from both sides.

and every step of the way I have a new combination (D'A, T'b, P'a...)

You don't need to cover each combination separately. Backreferences of the form \1, \2 are useful here:

sed "s/\([^,]\)'\([^,]\)/\1\\\'\2/g"
#      ^^^^^^^^                       The 1st capture group (it matches not-a-comma)...
#                        ^^           ... is referenced here by \1.
#               ^^^^^^^^              And the 2nd one...
#                              ^^     ... is referenced here by \2.
5
  • for some reason it is not replacing the text, but printing it.... any clue why?
    – Walucas
    Feb 17, 2019 at 17:02
  • @Walucas Because I omitted -i to make the answer more general; and to avoid making permanent changes in case it was wrong. I admit I assumed you know what -i does, since you used it in the first place. Feb 17, 2019 at 17:32
  • its one of my first times using sed, but I did try with -i but it failed somehow....
    – Walucas
    Feb 18, 2019 at 19:10
  • @Walucas Very basic question: did you give the command a file to operate on? Feb 18, 2019 at 19:18
  • hehehe, yes I did :)
    – Walucas
    Feb 19, 2019 at 15:17

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.