Size: 722
Comment: minor clean-up
|
Size: 1001
Comment: fixes, link to 100
|
Deletions are marked like this. | Additions are marked like this. |
Line 1: | Line 1: |
[[Anchor(faq41)]] | <<Anchor(faq41)>> |
Line 3: | Line 3: |
In [[BASH]]: | |
Line 5: | Line 6: |
# Bash | |
Line 8: | Line 10: |
The above works in virtually all versions of Bash. Bash version 3 also allows regular expressions: | The above works in virtually all versions of Bash. Bash version 3 (and up) also allows regular expressions: |
Line 11: | Line 13: |
if [[ $foo =~ ab*c ]] # bash 3, matches abbbbcde, or ac, etc. | # Bash my_re='ab*c' if [[ $foo =~ $my_re ]] # bash 3, matches abbbbcde, or ac, etc. |
Line 13: | Line 17: |
For more hints on string manipulations in Bash, see [[BashFAQ/100|FAQ #100]]. |
|
Line 17: | Line 23: |
# Bourne | |
Line 22: | Line 29: |
{{{case}}} allows you to match variables against globbing-style patterns. If you need a portable way to match variables against regular expressions, use {{{grep}}} or {{{egrep}}}. | {{{case}}} allows you to match variables against [[glob|globbing]]-style patterns (including extended globs, if your shell offers them). If you need a portable way to match variables against [[RegularExpression|regular expressions]], use {{{grep}}} or {{{egrep}}}. |
Line 25: | Line 32: |
if echo "$foo" | grep bar >/dev/null; then ... | # Bourne if echo "$foo" | grep bar >/dev/null 2>&1; then ... |
Line 27: | Line 35: |
---- CategoryShell |
How do I determine whether a variable contains a substring?
In BASH:
# Bash if [[ $foo = *bar* ]]
The above works in virtually all versions of Bash. Bash version 3 (and up) also allows regular expressions:
# Bash my_re='ab*c' if [[ $foo =~ $my_re ]] # bash 3, matches abbbbcde, or ac, etc.
For more hints on string manipulations in Bash, see FAQ #100.
If you are programming in the BourneShell instead of Bash, there is a more portable (but less pretty) syntax:
# Bourne case "$foo" in *bar*) .... ;; esac
case allows you to match variables against globbing-style patterns (including extended globs, if your shell offers them). If you need a portable way to match variables against regular expressions, use grep or egrep.
# Bourne if echo "$foo" | grep bar >/dev/null 2>&1; then ...