-1

I have a variable containing a string with a quote:

echo $variable
It's my variable

to be able to use this variable as a legend for ffmpeg, I need to add 5 backslashes before the quote:

variable="It\\\\\'s my variable"

I'm confused as to what syntax I should use, as the backslashes and quotes have very specific meanings in bash replace commands. I have tried this:

variable=`echo $variable | tr "'" "\\\\\'"`

but it does not produce the correct result

Sulli
  • 763
  • 1
  • 11
  • 33
  • Are you sure you need five backslashes? I think that maybe you just need to quote the variable when you use it in your `ffmpeg` command – Tom Fenech May 08 '17 at 10:27
  • @TomFenech I take that from http://stackoverflow.com/questions/10725225/ffmpeg-single-quote-in-drawtext/10729560 – Sulli May 08 '17 at 10:32
  • You shouldn't ever have an odd number of backslashes. – 123 May 08 '17 at 10:35
  • 1
    Per Tom's comment, I'd be very interested to see what it is you're doing that requires five backslashes. Can you please include how you're using `$variable` in your question? This sounds very much like an [XY Problem](http://mywiki.wooledge.org/XyProblem). Let's fix the underlying issue, rather than help you figure out how to do this the wrong way. :-) – ghoti May 08 '17 at 10:35
  • 1
    You could use an ansi c string. `$'It\'s my variable'` – 123 May 08 '17 at 10:36
  • @ghoti it all comes from this answer I'm linking to, in which there are five backslashes: http://stackoverflow.com/a/10729560/1967110 – Sulli May 08 '17 at 10:37
  • It's likely that the number of escapes that you will need will be different because that answer described a manual command line invocation and you're using variable expansion. Be prepared to do some testing. – ccarton May 08 '17 at 10:52

2 Answers2

3

You can just use some single quotes yourself to tell bash not to interpret those slashes:

variable="It"'\\\\\'"'s my variable"

Edit: To convert an existing variable use:

variable=${variable//\'/'\\\\\'\'}
ccarton
  • 3,556
  • 16
  • 17
  • the problem is that my variable gets its content from a file, I am not defining it myself. so I really need a way to escape the quote after the variable has been created – Sulli May 08 '17 at 10:34
0

This works fine, is portable and does not have the problems of sed:

echo "$v" |perl -pe "s/'/\x5c\x5c\x5c\x5c\x5c'/g"

PS: \x5c is the ascii code of slash \

George Vasiliou
  • 6,130
  • 2
  • 20
  • 27