home

Quickies, by Andrea Olivato

text

How to check if a string contains an other in #bash

Quick trick using #grep in #bash for checking if a string is contained in an other one

STRING="someUnknownString";
NAIL="know";

res=`echo $STRING | grep $NAIL`;
if [[ ${#res} > 0 ]];
then
	echo "Yes I found it.";
else
	echo "No way, there isn't."
fi

If you want you can make the whole thing case insensitive just using grep -i

STRING="someUnknownString";
NAIL="Unkn";

res=`echo $STRING | grep -i $NAIL`;
if [[ ${#res} > 0 ]];
then
	echo "Yes I found it.";
else
	echo "No way, there isn't."
fi

Lorenzo Sfarra on IdentiCa suggested me a quicker way to obtain the same result with less code. You can find this nicer way below…

STRING="someUnknownString";
NAIL="Unkn";
echo $STRING | grep -qi $NAIL && echo "Yes, I found it." || echo "no way, there isn't."

2 years ago

June 22, 2009
Comments (View)
blog comments powered by Disqus