Although I am almost sure this has been covered, I can\'t seem to find anything specific to this. As I continue my journey on learning bash I keep finding parts where I am b
I made this simple function:
match() {
TRUE=1
FALSE=0
match_return=0
echo $1 | grep $2 >/dev/null
[ $? -eq 0 ] && match_return=$TRUE || match_return=$FALSE
}
Usage:
match Testing Test ; [ $match_return -eq 1 ] && echo "match!" || echo "nope"
entire code: https://gist.github.com/TeeBSD/5121b3711fad40a09455
For quick string searches ... One option is grep.
If not found, returns empty, else it is a match:
found=`echo $big | grep -e $short`
if [ ! -z $found ]; then echo 'There is a match'; else echo 'No no'; fi
You can use the BASH_REMATCH
variable in bash
to get the matched string:
$ Stext="Hallo World"
$ [[ $Stext =~ ^.[a-z]* ]] && echo $BASH_REMATCH
Hallo
$ [[ $Stext =~ ^(.[a-z]*) ]] && echo ${BASH_REMATCH[1]}
Hallo
Substrings matched by parenthesized subexpressions within the regular expression are saved in the array variable BASH_REMATCH. The element of BASH_REMATCH with index 0 is the portion of the string matching the entire regular expression. The element of BASH_REMATCH with index n is the portion of the string matching the nth parenthesized subexpression.
Both expressions are equivalent, the difference is the regular expression you use:
$ echo `expr "$Stext" : '^\(.[a-z]*\)'`
Hallo
$ echo `expr "$Stext" : '^.[a-z]*'`
5
$ echo `expr "$Stext" : '\(.*World\)'`
Hallo World
$ echo `expr "$Stext" : '.*World'`
11
As you can see, parentheses is what makes the difference to either return the length of the match or the match itself.
You can find more examples in Chapter 10 of the Advanced Bash-Scripting Guide.