4

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?

2
  • 2
    Just remove the last / from "${category//\// /}". Like this: category="${category//\// }" Commented Nov 18, 2022 at 5:58
  • 2
    It is far too easy to confuse sed's s/this/that/g with bash's ${var//this/that} if you don't use both in roughly equal measure, I have found.
    – DopeGhoti
    Commented Nov 18, 2022 at 6:56

1 Answer 1

8

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
2
  • 1
    Note that that syntax comes from ksh93. ${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
  • @StéphaneChazelas interesting! What's old is new again. Presumably with tcsh's :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

You must log in to answer this question.

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