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
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
The correct substitution is
home_mf="${home//\\//}"
This breaks up as follows:
// replace every\\ backslash/ with/ slashDemonstration:
$ 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//'\'/"/"}"
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