Bash allows checking for a substring.
It is even possible to use the wildcard symbol *
inside the search string:
# works
line="foo bar baz"
if [[ $line == *"foo "*" baz"* ]]; then
echo "found"
fi
1.) But how do I pass the search string including the wildcard through a variable?
# fails
line="foo bar baz"
search='foo "*" baz'
echo "$search"
if [[ $line == *"$search"* ]]; then
echo "found"
fi
2.) And if it is possible through escaping: How do I manipulate $search
, so the user of my script can simply pass foo * baz
?
The only solution I found is this, but it is limited to a specific maximum amount of wildcards and it does not feel like the best way to solve this:
line="foo bar baz"
search="foo * baz"
IFS=\* read -r search1 search2 search3 search4 <<< "$search"
if [[ $line == *"$search1"*"$search2"*"$search3"*"$search4"* ]]; then
echo "found"
fi