Bash Substring Verification

by on July 17, 2009 · 0 comments· last updated at July 17, 2010

How can I find out whether a variable called $vech contains a substring called 'car' under bash?

vech='car bus bike rail airplane'


Use the following syntax:

[[ $vech = *car* ]] && echo "Car found in \$vech" || echo "Sorry"

You can also use the following syntax:

 
  case "$vech" in
    *car*) echo "Car found, do something" ;;
    *bus*) echo "call bus()";;
   *) echo "Error..."
  esac
 

You can use grep to display matching pattern only:
grep -o "car" <<<"$vech"
OR
echo "$vech" | grep -o "car"



You should follow me on twitter here or grab rss feed to keep track of new changes.

Featured Articles:

{ 0 comments… add one now }

Leave a Comment

You can use these HTML tags and attributes for your code and commands: <strong> <em> <ol> <li> <u> <ul> <kbd> <blockquote> <pre> <a href="" title="">

Tagged as: , , , , , , , ,

Previous Faq:

Next Faq: