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.
grep -q
is useful for this purpose.The same using
awk
:Output:
Output:
Original source: http://unstableme.blogspot.com/2008/06/bash-search-letter-in-string-awk.html
Exact word match:
You should remember that shell scripting is less of a language and more of a collection of commands. Instinctively you think that this "language" requires you to follow an
if
with a[
or a[[
. Both of those are just commands that return an exit status indicating success or failure (just like every other command). For that reason I'd usegrep
, and not the[
command.Just do:
Now that you are thinking of
if
as testing the exit status of the command that follows it (complete with semi-colon). Why not reconsider the source of the string you are testing?The
-q
option makes grep not output anything, as we only want the return code.<<<
makes the shell expand the next word and use it as the input to the command, a one-line version of the<<
here document (I'm not sure whether this is standard or a bashism).I found to need this functionality quite frequently, so I'm using a home-made shell function in my
.bashrc
like this which allows me to re-use it as often as I need to, with an easy to remember name:To test if
$string1
(say, abc) is contained in$string2
(say, 123abcABC) I just need to runstringinstring "$string1" "$string2"
and check for the return value, for exampleIf you prefer the regex approach:
Try oobash it is an OO-style string library for bash 4. It has support for German umlauts. It is written in bash. Many functions are available:
-base64Decode
,-base64Encode
,-capitalize
,-center
,-charAt
,-concat
,-contains
,-count
,-endsWith
,-equals
,-equalsIgnoreCase
,-reverse
,-hashCode
,-indexOf
,-isAlnum
,-isAlpha
,-isAscii
,-isDigit
,-isEmpty
,-isHexDigit
,-isLowerCase
,-isSpace
,-isPrintable
,-isUpperCase
,-isVisible
,-lastIndexOf
,-length
,-matches
,-replaceAll
,-replaceFirst
,-startsWith
,-substring
,-swapCase
,-toLowerCase
,-toString
,-toUpperCase
,-trim
, and-zfill
.Look at the contains example:
oobash is available at Sourceforge.net.