Pal Csanyi
Pal Csanyi

Reputation: 101

Removing substring from string variable in bash

I have a bash string variable:

switches="-r cc -c 1,2,3,4 -u"

where numbers 1,2,3,4 can be any integer, like:

-c 25,45,78,34.

Moreover, it can be with fewer numbers, like:

-c 1

-c 1,2

or

-c 1,2,3,4

It can't be like: -c 1,2,3

So -c can have one, two, or four integers only.

I forgot to mention that that this pattern can appeares also at the beginning, or at the end of the string variable $switches too, like:

-r cc -u -c 1,2,3,4

-r cc -u -c 1,2,3

And one more thing: this pattern can be appeared in the $switches variable only once.

How can I remove the '-c 1,2,3,4 ' part of switches variable using just bash? I tried with this:

switches=${switches/ -c /}

but get this:

-r cc1,2,3,4 -u

I expect this:

-r cc -u

Best, Pal

Upvotes: 0

Views: 125

Answers (1)

PesaThe
PesaThe

Reputation: 7499

Using extglob:

shopt -s extglob                         # enables extended globbing
switches=${switches//-c *([^ ])}
  • *([^ ]): matches any number of non-spaces

This will leave you with unnecessary spaces. More complicated solution:

switches=${switches//-c *([^ ])*( )}
switches=${switches/%*( )}
  • *([^ ])*( ): matches any number of non-spaces and any number of spaces after
  • ${switches/%*( )}: if the last option is also -c, the code above wouldn't remove the spaces left by it. /%*( ) removes any number of spaces from the end

Upvotes: 1

Related Questions