Posted By

symsec on 10/20/12


Tagged

regex Bash pattern match expansion extglob globbing


Versions (?)

Bash pattern matching using extended globbing


 / Published in: Bash
 

Using a (faster) case structure to do bash built-in pattern matching. See Bash hackers for more information. Thanks to gnashley for the snippet.

  1. #!/bin/sh
  2.  
  3. thisString="1 2 3 4 5"
  4. searchString="1 2"
  5.  
  6. # if you single quote your input, you could do this
  7. # searchString=$1
  8.  
  9. case $thisString in
  10.  
  11. # match exact string
  12. "$searchString") echo yep, it matches exactly;;
  13.  
  14. # match start of string
  15. "$searchString"*) echo yep, it matches at the start ;;
  16.  
  17. # match end of string
  18. *"$searchString") echo yep, it matches at the end ;;
  19.  
  20. # searchString can be anywhere in thisString
  21. *"$searchString"*) echo yep, it matches in the middle somewhere ;;
  22.  
  23. *) echo nope ;;
  24.  
  25. esac

Report this snippet  

You need to login to post a comment.