Piping paths with different types of quotes for slash substitution

I would like to use sed to convert a path with backslashes to the same path with forward slashes:

E.g. I would like to pipe \\path\to\file\ and obtain /path/to/file

None of the following commands work, and I can't tell why:

First attempt:

> echo '\\path\to\file\' | sed 's/\\/\//g'
/path   o
ile/


Second attempt:

echo \\path\to\file\ | sed 's/\\/\//g'
/pathtofile


Third attempt:

 echo "\\path\to\file\" | sed 's/\\/\//g'
dbquote>


I get a similar behavior if I try piping to | tr '\' '/'

I am looking for the correct answer and, if possible, for an explanation of why none of the attempts above worked. Not sure if it matters, but this is all on zsh 4.2.6 (x86_64-redhat-linux-gnu)

Thanks!

-
I'd recommend using a different delimiter with sed than / when you're dealing with path delimiters. This works here with GNU sed in zsh: echo '\\path\to\file\' | sed -r 's:\\+:/:g'. – Thor Sep 11 '12 at 14:23
What version of zsh are you using? – Thor Sep 11 '12 at 14:24
@Thor, I just updated the OP to include the version – user815423426 Sep 11 '12 at 14:26

file='\\path\to\file\'
printf '%s\n' "$file" | tr -s '\\' /  zsh: setopt extendedglob print -r --${file//\\##/\/}

-

Don't use echo. The problem with echo is there are too many versions and each handles backslashes slightly differently. Yours is evidently interpreting the backslashes in your original string. If you just did

# first attempt
echo '\\path\to\file\'


I suspect you would see

\path   o
ile\


Similarly in all your other attempts the problem is with your usage of echo and the interactions between echo and shell quoting and backslashes, and not with the second part of the pipe (the sed or tr).

The solution is to use printf instead - its behavior is much more consistent and portable since it is specified by POSIX.

printf '\\\\path\\to\\file\\\n'


gets you

\\path\to\file\

-
 Thanks, do I need to add an extra backslash for each backslash for printf to work? It would be great to have a solution that directly works with paths "as they are typed in windows". – user815423426 Sep 11 '12 at 14:19 I copy them from my local Windows OS onto a VNC session that is connected to a remote machine, but I get the same problem if I type the backslashes myself manually. – user815423426 Sep 11 '12 at 14:25 I am hoping to write a zsh function that takes the windows path as an input argument and cds into that path on the remote filesystem (the function will have to change the anchor point and the backslashes to forward slashes to be able to cd into the folder) – user815423426 Sep 11 '12 at 14:28 @roseck Sounds like a job for parameter expansion, not echo | sed. For example, try path='\\path\to\file'; printf 'cd'ing to %s\n' "\${path//\\//}";. See also the X-Y Problem. – jw013 Sep 11 '12 at 14:31