I would like to know a neat way in which I can check to see if a string is there in a comma separated value of strings. eg: if
x="abc,def,ghi"
y="abc"
it should return true
and if
y="ab"
then it should return false
You could use globs:
[[ ",$x," = *",$y,"* ]]
Use bash's regular-expression-matching operator, =~
:
[[ $x =~ (^|,)"$y"(,|$) ]]
Caveat: While the above regex happens to be portable, the particular flavor of regular expressions supported by =~
is platform-dependent due to use of a given platform's regex libraries.
Case in point: hek2mgl suggests use of \b
to match word boundaries, which works on Linux, but not OSX, for instance. The closest thing to \b
in POSIX are [[:<:]]
and [[:>:]]
, but, unfortunately, these don't work on Linux.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With