Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: BUG? - 4.0.2 - parameter substitution won't double backslashes in values



On Thu, 7 Feb 2002, Derek Peschel wrote:

> Maybe my explanation was too complicated, or probably you missed the
> beginning of the thread.

I saw the beginning of the thread, and I saw Sven's answer, which didn't
seem to bear repeating, so I was responding only to the parenthetical
comment about backspace changing to "\b".  As Sven's answer apparently
does bear repeating:

> I have a string containing the characters "a", backslash, "b", "c".
[...]
> I want to use parameter substitution to convert the backslash to two
> backslashes.

You *probably* want the (q) parameter flag:

zsh% x='a\bc'
zsh% print ${(q)x}
a\bc
zsh% print -r ${(q)x}
a\\bc

However, (q) will also insert a backslash in front of any other character
that is special to the shell parser.  If you want *only* to double all the
backslashes, you need one of:

zsh% print -r ${x//\\\/\\\\}
a\\bc
zsh% print -r ${x:gs/\\/\\\\\\\\}
a\\bc

The reason you need three backslashes as the pattern in the first case is
rather complicated and could possibly be considered a bug; it has to do
with using glob-pattern interpretation in ${x//...}.  The reason you need
eight backslashes as the replacement in the second case is a lot easier to
explain; the eight are reduced to four by the initial parse of the shell
command line, and then reduced again to two when the :gs replacement
occurs.

The second one is probably more reliable, as it works the same even if the
expansion is enclosed in double quotes.



Messages sorted by: Reverse Date, Date, Thread, Author