Search code examples
bashglob

Remove specified string pattern(s) from a string in bash


I found a good answer that explains how to remove a specified pattern from a string variable. In this case, to remove 'foo' we use the following:

string="fooSTUFF"
string="${string#foo}"

However, I would like to add the "OR" functionality that would be able to remove 'foo' OR 'boo' in the cases when my string starts with any of them, and leave the string as is, if it does not start with 'foo' or 'boo'. So, the modified script should look something like that:

string="fooSTUFF"
string="${string#(foo OR boo)}"

How could this be properly implemented?


Solution

  • You need an extended glob pattern for that (enabled with shopt -s extglob):

    $ str1=fooSTUFF
    $ str2=booSTUFF
    $ str3=barSTUFF
    $ echo "${str1#@(foo|boo)}"
    STUFF
    $ echo "${str2#@(foo|boo)}"
    STUFF
    $ echo "${str3#@(foo|boo)}"
    barSTUFF
    

    The @(pat1|pat2) matches one of the patterns separated by |.

    @(pat1|pat2) is the general solution for your question (multiple patterns); in some simple cases, you can get away without extended globs:

    echo "${str#[fb]oo}"
    

    would work for your specific example, too.