Size: 747
Comment: add link
|
Size: 912
Comment: Code: adjust if, simplify expr
|
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* ]] | if [[ $foo == *bar* ]]; then ... fi |
Line 8: | Line 11: |
The above works in virtually all versions of Bash. Bash version 3 also allows regular expressions: | Portable POSIX sh syntax: |
Line 11: | Line 14: |
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 *bar*) .... ;; |
case $foo in *bar*) ... ;; |
Line 22: | Line 20: |
{{{case}}} allows you to match variables against [:globbing:]-style patterns. If you need a portable way to match variables against [:RegularExpression: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 3.x or later, to match using regular expressions: |
Line 25: | Line 25: |
if echo "$foo" | grep bar >/dev/null; then ... | # matches e.g ac, abc and abbbbc re='ab*c' if [[ $foo =~ $re ]]; then ... fi |
Line 27: | Line 31: |
Portable POSIX sh syntax to match using [[RegularExpression|regular expressions]]. Notice that the initial ".*" is required: {{{ if expr "$foo" : ".*$re" > /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:
if [[ $foo == *bar* ]]; then ... fi
Portable POSIX sh syntax:
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 3.x or later, to match using regular expressions:
# matches e.g ac, abc and abbbbc re='ab*c' if [[ $foo =~ $re ]]; then ... fi
Portable POSIX sh syntax to match using regular expressions. Notice that the initial ".*" is required:
if expr "$foo" : ".*$re" > /dev/null then ... fi
For more hints on string manipulations in Bash, see FAQ #100.