Friday, 11 August 2017

How to check if a string contains a substring in Bash



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.


Answer




You can use Marcus's answer (* wildcards) outside a case statement, too, if you use double brackets:



string='My long string'
if [[ $string == *"My long"* ]]; then
echo "It's there!"
fi


Note that spaces in the needle string need to be placed between double quotes, and the * wildcards should be outside.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...