1

I have to replace all slashes, antislashes, single and double quotes in a variable, possibly in on pass, with their escaped version:

' --> \'
" --> \"
\ --> \\
/ --> \/

At this point, I use this to replace single quote:

${MYVAR//\'/\\\'}

But I'm stucked when I'm trying to replace slashes, antislashes, single and double quotes in one pass.

Will Vousden
  • 32,488
  • 9
  • 84
  • 95
Zax
  • 169
  • 3
  • 12
  • If you're trying to escape a string for use as shell input, you could try [`printf '%q' "$MYVAR"`](https://stackoverflow.com/questions/40573839/how-to-use-printf-q-in-bash) (if your bash supports it). – Will Vousden Jul 03 '17 at 08:57
  • It's for use in a Synology NAS script: I have to send the value of a variable from bash by mail using PHP engine. Of course, PHP returns an error with nested quotes. – Zax Jul 03 '17 at 11:17

1 Answers1

0

You could use sed replace:

echo "'\"\\/" | sed "s~\(['\"\/]\)~\\\\\1~g"

Edit according to the comments:

EXPLORE_FOLDER="/volume1/video/myMovies"
LS_LIST="$(ls --recursive "$EXPLORE_FOLDER")"
RESULT="$(sed "s~\(['\"\/]\)~\\\\\1~g" <<<"$LS_LIST")"
echo "$RESULT"

Or just:

EXPLORE_FOLDER="/volume1/video/myMovies"
RESULT="$(ls --recursive "$EXPLORE_FOLDER" | sed "s~\(['\"\/]\)~\\\\\1~g" <<<"$LS_LIST")"
echo "$RESULT"
Pavel
  • 182
  • 1
  • 9
  • Thanks Pavel, but I'm a totally newbie... Where is MYVAR in you sed solution? – Zax Jul 03 '17 at 11:12
  • @Zax Like this: `echo "$MYVAR" | sed ...` – Will Vousden Jul 03 '17 at 11:55
  • Or, better still, use a [herestring](https://unix.stackexchange.com/questions/76402/command-line-instead-of) to avoid creating unnecessary processes: `sed ... <<<"$MYVAR"` – Will Vousden Jul 03 '17 at 11:56
  • @will ahem... I'm unable to make it work. I used: `EXPLORE_FOLDER="/volume1/video/myMovies" LS_LIST=$(ls --recursive "$EXPLORE_FOLDER") sed "'\"\\/" | "s~\(['\"\/]\)~\\\\\1~g" <<<"$LS_LIST" echo $LS_LIST` (LS_LIST must be emailed later). – Zax Jul 03 '17 at 13:56
  • @Zax I just updated my answer to match the example you provided. – Pavel Jul 04 '17 at 11:52
  • @Pavel Thank you very much! (btw, I also found then I couldn't send too large variable as message to php, but it's another problem). – Zax Jul 04 '17 at 13:17