29

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
3
  • This belongs on UNIX.SE Commented Dec 28, 2017 at 6:47
  • @Dan, why? This is standard Bash, and not platform-specific. Commented May 27, 2019 at 8:28
  • It might be more appropriate on Stack Overflow, since it can be considered a programming question. Commented Nov 23, 2022 at 7:58

2 Answers 2

51

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 ('\' rather than \\) and the replacement ("/" rather than plain /):

home_mf="${home//'\'/"/"}"
1
  • 2
    Nice regex break-up to a human readable sentence :) . Commented Dec 3, 2021 at 12:35
12

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
3
  • doesn't work echo "output: $home_mf" returns "output: homeuser" for "/home/user"
    – Para
    Commented Apr 21, 2016 at 7:46
  • 1
    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
    Commented Apr 21, 2016 at 8:38
  • Might be an idea to use a different character as separator in the sed s command, e.g. s,/,\\,g and s,\\,/,g. Commented Nov 5, 2020 at 17:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .