Size: 730
Comment:
|
Size: 853
Comment: Simplify. Rm text "expr utility", already shown in code
|
Deletions are marked like this. | Additions are marked like this. |
Line 1: | Line 1: |
[[Anchor(faq41)]] | <<Anchor(faq41)>> |
Line 3: | Line 3: |
in [[BASH]], to match using pattern matching: | |
Line 5: | Line 6: |
if [[ $foo = *bar* ]] | # Bash if [[ $foo == *bar* ]] |
Line 8: | Line 10: |
The above works in virtually all versions of Bash. Bash version 3 also allows regular expressions: | Portable POSIX sh syntax: |
Line 11: | Line 13: |
if [[ $foo =~ ab*c ]] # bash 3, matches abbbbcde, or ac, etc. }}} If you are programming in the BourneShell instead of Bash, there is a more portable (but less pretty) syntax: {{{ case "$foo" in |
# Bourne case $foo in |
Line 22: | Line 19: |
This should allow you to match variables against globbing-style patterns. if you need a portable way to match variables against regular expressions, use {{{grep}}} or {{{egrep}}}. | The {{{case}}} allows matching variables against [[glob|globbing]]-style patterns. In Bash, and some shells, there is also extended globs. In Bash, to match using regular expressions: |
Line 25: | Line 24: |
if echo "$foo" | egrep some-regex >/dev/null; then ... | # Bash 3.x # matches e.g ac, abc and abbbbc re='ab*c' if [[ $foo =~ $re ]] |
Line 27: | Line 29: |
Portable POSIX sh syntax to match using [[RegularExpression|regular expressions]]: {{{ # POSIX if expr "x$foo" : 'x.*bar' > /dev/null then ... fi }}} For more hints on string manipulations in Bash, see [[BashFAQ/100|FAQ #100]]. ---- CategoryShell |
How do I determine whether a variable contains a substring?
in BASH, to match using pattern matching:
# Bash if [[ $foo == *bar* ]]
Portable POSIX sh syntax:
# Bourne case $foo in *bar*) .... ;; esac
The case allows matching variables against globbing-style patterns. In Bash, and some shells, there is also extended globs.
In Bash, to match using regular expressions:
# Bash 3.x # matches e.g ac, abc and abbbbc re='ab*c' if [[ $foo =~ $re ]]
Portable POSIX sh syntax to match using regular expressions:
# POSIX if expr "x$foo" : 'x.*bar' > /dev/null then ... fi
For more hints on string manipulations in Bash, see FAQ #100.