I have a scripting problem that I'm trying to solve, whereby I want to match that a string contains either of three strings. I'm thinking this is probably just me not understanding how to craft the appropriate regex. However, here's what I would like to do:
[[ $STRING =~ "one|two|three" ]] && do-something
more specifically:
[[ $STRING =~ "one OR two OR three" ]] && do something || :
I'd like to be able to match based on whether it has one or more of those strings -- or possibly all.
I'm sure this is simple, I just can't get my brain around it.
I know that BASH =~ regex can be system-specific, based on the libs available -- in this case, this is primarily CentOS 6.x (some OSX Mavericks with Macports, but not needed)
The string will actually be a part of a hostname, for example "one-hostname" or something like that. I need it check that there's a match, possibly doing something based on what it matched. But in this case the match word will be at the beginning ^one.
That is a string match, not a regex match see other comments...
Where did you get that idea? That is not correct.. It does depend on bash version. Old versions of bash cannot process =~ , (but a case statement using unix patterns will work)
$ echo $BASH_VERSION
4.1.10(4)-release
p='^(one|two|three)$'
$ for s in one two three "$p"; do
> [[ $s =~ $p ]] && printf '%s matches %s\n' "$s" "$p"
> [[ $s =~ "$p" ]] && printf '%s matches "%s"\n' "$s" "$p"
> done
one matches ^(one|two|three)$
two matches ^(one|two|three)$
three matches ^(one|two|three)$
^(one|two|three)$ matches "^(one|two|three)$"
As I said, when you quote the regular expression, it's taken literally.
As far as I know, the =~ operator is bash version specific
(i.e. it's not available in older bash versions).
There are some other gotchas and some platform specific issues, see the BashWiki for more info (see Portability Considerations).
should not produce any output. If you're trying to match one , two , or three at the start of the string and accept anything following one of those three strings, you don't want the $ . With the $ , the RE matches only if one of those three strings is the entire contents of $STRING .