The SQL applications that I'm using isn't properly escaping all of the strings that I have, so I'm trying to use sed to replace these instances. The issue is I'll have this:
`some string of characters that may include hyphens'
and the quote at the end won't get escaped (yes that's supposed to be a ` not a quote).
My plan was to use this:
sed 's/[^\\]\'[^,]/&\\\'&/g' testfile.txt
Logic: anything that isn't a backslash followed by a quote, then anything that isn't a comma will be replaced by the same text with with a backslash and a quote.
I would like for testfile.txt to have all instances of ' replaced with \', but I just keep getting > as if it isn't done the line
答案 0 :(得分:0)
What you're looking for are called lookaround assertions, where you match any '
not preceded by a \
or followed by an end of line. Unfortunately, sed doesn't support these. But you can use Perl:
perl -pe 's/(?<!\\)'\''(?!$)/\\'\''/g' testfile.txt
In unescaped form, this would look like s/(?<!\\)'(?!$)/\\'/g
but we have to make allowances for the shell. No escapes are recognized in single quoted strings, so your original problem was \'
not being recognized, and the string terminating early.
See here for example and detailed regexp breakdown: https://regex101.com/r/k8sonu/1
答案 1 :(得分:0)
I try this using gnu sed,
$ cat d
already escaped quote \' won't be escaped
$ sed -E "s/([^\\]|^)'([^,]|$)/\1\\\'\2/" d
already escaped quote \' won\'t be escaped