7

I have the following string

str="toto1 toto2 toto3 toto4 toto2 toto5"

the toto2 occurs twice in the string. How can I remove all toto2 occurrences from the string?

I tried this:

echo ${str/toto2/}

But this will remove only the first occurrence of toto2.

toto1 toto3 toto4 toto2 toto5 # output

How can I remove all toto2 occurrences from the string?

codeforester
  • 39,467
  • 16
  • 112
  • 140
MOHAMED
  • 41,599
  • 58
  • 163
  • 268
  • 1
    FYI, if you want a set abstraction in bash, it's better to use bash 4's associative arrays rather than strings for the purpose. – Charles Duffy Dec 26 '13 at 15:14
  • Vaguely related: [Bash string manipulation -- removing characters?](https://stackoverflow.com/questions/23047934/bash-string-manipulation-removing-characters) asks about trimming a temperature expression to just the actual floating-point number. – tripleee Aug 24 '22 at 05:00

1 Answers1

17

Found it. The solution is:

echo "${str//toto2/}"
tripleee
  • 175,061
  • 34
  • 275
  • 318
MOHAMED
  • 41,599
  • 58
  • 163
  • 268
  • @anishsane ABS is not a great reference -- it shows a lot of bad practices in its examples. Better to point folks at http://mywiki.wooledge.org/BashFAQ/073 – Charles Duffy Dec 26 '13 at 15:13
  • I linked to the Bash reference manual, and added the missing quotes. See also [When to wrap quotes around a shell variable](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable) – tripleee Aug 24 '22 at 05:02