Differences between revisions 4 and 16 (spanning 12 versions)
Revision 4 as of 2008-05-16 20:00:06
Size: 747
Editor: GreyCat
Comment: add link
Revision 16 as of 2025-04-10 22:22:40
Size: 912
Editor: 81
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 B
ash 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.


CategoryShell

BashFAQ/041 (last edited 2025-04-19 15:51:39 by StephaneChazelas)