13

I want to replace backslash(\) with forward slash(/) in a variable in bash. I tried it like this, but it doesn't work:

home_mf = ${home//(\)//(/)}

For example, I would like

\a\b\c -> /a/b/c
  • This belongs on UNIX.SE – Dan Dascalescu Dec 28 '17 at 6:47
  • @Dan, why? This is standard Bash, and not platform-specific. – Toby Speight May 27 '19 at 8:28
23

The correct substitution is

home_mf="${home//\\//}"

This breaks up as follows:

  • // replace every
  • \\ backslash
  • / with
  • / slash

Demonstration:

$ t='\a\b\c'; echo "${t//\\//}"
/a/b/c

An alternative that may be easier to read would be to quote the pattern and the replacement:

home_mf="${home//'\'/"/"}"
8

This will do it:

home_mf=${home//\//\\} # forward to backward slash
home_mf=${home//\\//} # backward to forward slash

e.g.:

$ cat slash.sh
#!/bin/bash
set -x
home=/aa/bb/cc       
home_mf=${home//\//\\}
echo $home_mf
home_mf=${home_mf//\\//}
echo $home_mf
$ ./slash.sh
+ home=aa/bb/cc
+ home_mf='\aa\bb\cc'
+ echo '\aa\bb\cc'
\aa\bb\cc
+ home_mf=/aa/bb/cc
+ echo /aa/bb/cc
/aa/bb/cc

The ${variable/..} syntax is ksh, bash, and possibly other shells specific but is not be present in all Bourne shell syntax based shells, e.g. dash. Should you want a portable way (POSIX), you might use sed instead:

home_mf=$(printf "%s" "$home" | sed 's/\//\\/g')    # forward to backward slash
home_mf=$(printf "%s" "$home_mf" | sed 's/\\/\//g') # backward to forward slash
  • doesn't work echo "output: $home_mf" returns "output: homeuser" for "/home/user" – Para Apr 21 '16 at 7:46
  • Answer edited to demonstrate it works with me. Not sure what happens in your case, try using printf "%s\n" "$home_mf" instead of echo "$home_mf". – jlliagre Apr 21 '16 at 8:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.