I'm trying to replace slashes with a space:
category='dir1/dir2/dir3'
category="${category//\// /}"
echo $category
dir1 /dir2 /dir3
I'd like to get dir1 dir2 dir3
.
How can I get this using Bash?
The "replace all" syntax in bash
is ${variable//OLD/NEW}
, with no trailing slash. The slash you have there right now is considered part of the replacement, so you're replacing each slash with space-slash, not just with a space. Remove the final slash to get what you want:
$ category='dir1/dir2/dir3'
$ category="${category//\// }"
$ echo "$category"
dir1 dir2 dir3
${var//OLD/}
(to replace with nothing) can also be written ${var//OLD}
. See also the $var:s/old/new/
of csh which predates ksh's by decades and is much closer to ed
's s/re/new/
. Also supported by zsh but not by bash even though bash copied csh history expansion. For global subst, you need :as/old/new/
in tcsh and :gs/old/new/
in zsh.
Commented
Nov 18, 2022 at 11:37
:as
in the construct :as/old/new/
, the a
stands for all? Raku is using something similar to the zsh construct to represent substitute:global -- the Raku version is s:g/old/new/
.
Commented
Nov 20, 2022 at 7:13
/
from"${category//\// /}"
. Like this:category="${category//\// }"
sed
'ss/this/that/g
withbash
's${var//this/that}
if you don't use both in roughly equal measure, I have found.