Pass variable to sed and change backslash to forward slash

Inside the command substitution you have "$FILE" | sed -e 's/\\/\//gp', which the shell expands to (the equivalent of) '\\edi3\welshch\test' | sed -e 's/\\/\//gp'. Since it's a command, the shell goes looking for a file called \\edi3\welshch\test to run.

You probably meant to use echo "$FILE" | sed ... to pass the contents of FILE to sed via the pipe.

Note that even that's not right, some versions of echo will process the backslashes as escape characters, messing things up. You'll need printf "%s\n" "$FILE" | sed ... for it to work in all shells. See: Why is printf better than echo?

Also, note that the default behaviour of sed is to print the line after whatever operations it does. When you use /p on the s/// command, it causes an additional print, so you get the result twice in the output.

That said, since you're using Bash, you could just use the string replacement expansion:

#!/bin/bash
FILE='\\edi3\welshch\test'
FILEPATH=${FILE//\\//}
echo "$FILEPATH"

gives the output //edi3/welshch/test


The variable has to be output (by echo) to sed. Using sed -n to suppress sed output. Edit - don't need sed -n if we omit the sed p flag.

#!/bin/bash

FILE='\\edi3\welshch\test'

FILEPATH="$(echo "$FILE" | sed 's/\\/\//g')"
echo $FILEPATH

To substitute individual characters, it's simpler to use tr(1):

FILE=$(echo "$FILE" | tr '\\' / )

Tags:

Sed