I want to see if a string is inside a portion of another string.
e.g.:
'ab' in 'abc' -> true
'ab' in 'bcd' -> false
How can I do this in a conditional of a bash script?
I want to see if a string is inside a portion of another string.
e.g.:
'ab' in 'abc' -> true
'ab' in 'bcd' -> false
How can I do this in a conditional of a bash script?
[[ "bcd" =~ "ab" ]]
[[ "abc" =~ "ab" ]]
the brackets are for the test, and as it is double brackets, it can so some extra tests like
=~
.So you could use this form something like
Edit: corrected "=~", had flipped.
You can use the form
${VAR/subs}
whereVAR
contains the bigger string andsubs
is the substring your are trying to find:This works because
${VAR/subs}
is equal to$VAR
but with the first occurrence of the stringsubs
removed, in particular if$VAR
does not contains the wordsubs
it won't be modified.Using bash filename patterns (aka "glob" patterns)
The following two approaches will work on any POSIX-compatible environment, not just in bash:
Both of the above output:
The former has the advantage of not spawning a separate
grep
process.Note that I use
printf %s\\n "${foo}"
instead ofecho "${foo}"
becauseecho
might mangle${foo}
if it contains backslashes.shell case statement
This is the most portable solution, will work even on old Bourne shells and Korn shell
Sample run:
Note that you don't have to specifically use
echo
you can useexit 1
andexit 0
to signify success or failure.What we could do as well, is create a function (which can be used in large scripts if necessary) with specific return values ( 0 on match, 1 on no match):
grep
This particular approach is useful with if-else statements in
bash
. Also mostly portableAWK
Python
Ruby
Mind the
[[
and"
:So as @glenn_jackman said, but mind that if you wrap the whole second term in double quotes, it will switch the test to literal matching.
Source: http://tldp.org/LDP/abs/html/comparison-ops.html
Similar to edwin's answer, but with improved portability for posix & ksh, and a touch less noisy than Richard's:
Output: