0

I have a string S, for which I want to replace every b character with \\ (two forward slashes). So this is what I have:

$ S="abc"
$ A=$(echo $S | sed 's/b/\\\\/')

In bash I get the expected output:

$ echo $A
a\\c

but in zsh I have

$ echo $A
a\c

It seems to me that zsh's behavior is unexpected, why does it behave this way?

I want A to contain two forward slashes (so I can use it later as a regex, for example). How can I achieve this in a cross-shell way?

  • it does contain two *back*-slashes, you're just printing it with `echo` which in zsh treats backslashes specially. Try `echo 'foo\nbar'` in Bash and in zsh, and then do the same with `echo -e` and `echo -E`. – ilkkachu Jun 29 '22 at 07:18
  • See also the `xpg_echo` option in bash to make its `echo` UNIX compliant in that regard, and the `bsdecho` option in `zsh` to make it non-compliant. – Stéphane Chazelas Jun 29 '22 at 07:24
  • OTOH in both Bash and zsh you could use `A="${S/b/\\\\}"` instead of calling out to `sed`, see e.g. http://mywiki.wooledge.org/BashGuide/Parameters#Parameter_Expansion – ilkkachu Jun 29 '22 at 07:26

0 Answers0