I have a string in Bash:
string="My string"
How can I test if it contains another string?
if [ $string ?? 'foo' ]; then
echo "It's there!"
fi
Where ??
is my unknown operator. Do I use echo and grep
?
if echo "$string" | grep 'foo'; then
echo "It's there!"
fi
That looks a bit clumsy.
I like sed.
Edit, Logic:
Use sed to remove instance of substring from string
If new string differs from old string, substring exists
My .bash_profile and how I used grep if the PATH included my 2 bin dirs, don't append them
Bash4+ examples. Note: not using quotes will cause issues when words contain spaces etc.. Always quote in bash IMO.
Here are some examples BASH4+ :
Example 1, check for 'yes' in string (case insensitive):
Example 2, check for 'yes' in string (case insensitive):
Example 3, check for 'yes' in string (case sensitive) :
Example 4, check for 'yes' in string (case sensitive):
Example 5, exact match (case sensitive):
Example 6, exact match (case insensitive):
Example 7, exact match :
Example 8, wildcard match .ext (case insensitive) :
enjoy.
The accepted answer is best, but since there's more than one way to do it, here's another solution:
${var/search/replace}
is$var
with the first instance ofsearch
replaced byreplace
, if it is found (it doesn't change$var
). If you try to replacefoo
by nothing, and the string has changed, then obviouslyfoo
was found.So there are lots of useful solutions to the question - but which is fastest / uses the least resource?
Repeated tests using this frame:
Replacing TEST each time:
(doContain was in F. Houri's answer)
And for giggles:
So the simple substituion option predicatbly wins whether in an extended test or a case. The case is portable.
Piping out to 100000 greps is predictably painful! The old rule about using external utilities without need holds true.
One is: