如何在案例陈述中使用模式? [英] How to use patterns in a case statement?

查看:64
本文介绍了如何在案例陈述中使用模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

man页显示case语句使用文件名扩展模式匹配".
我通常希望对某些参数使用短名称,所以我去了:

The man page says that case statements use "filename expansion pattern matching".
I usually want to have short names for some parameters, so I go:

case $1 in
    req|reqs|requirements) TASK="Functional Requirements";;
    met|meet|meetings) TASK="Meetings with the client";;
esac

logTimeSpentIn "$TASK"

我尝试了像req*me{e,}t这样的模式,据我所知,它们可以正确扩展以匹配文件名扩展上下文中的那些值,但这是行不通的.

I tried patterns like req* or me{e,}t which I understand would expand correctly to match those values in the context of filename expansion, but it doesn't work.

推荐答案

括号扩展不起作用,但是*?[]起作用.如果设置shopt -s extglob,则还可以使用扩展模式匹配:

Brace expansion doesn't work, but *, ? and [] do. If you set shopt -s extglob then you can also use extended pattern matching:

  • ?()-零次或一次出现模式
  • *()-模式零次或多次出现
  • +()-出现一个或多个模式
  • @()-模式的一次出现
  • !()-除模式以外的任何内容
  • ?() - zero or one occurrences of pattern
  • *() - zero or more occurrences of pattern
  • +() - one or more occurrences of pattern
  • @() - one occurrence of pattern
  • !() - anything except the pattern

这是一个例子:

shopt -s extglob
for arg in apple be cd meet o mississippi
do
    # call functions based on arguments
    case "$arg" in
        a*             ) foo;;    # matches anything starting with "a"
        b?             ) bar;;    # matches any two-character string starting with "b"
        c[de]          ) baz;;    # matches "cd" or "ce"
        me?(e)t        ) qux;;    # matches "met" or "meet"
        @(a|e|i|o|u)   ) fuzz;;   # matches one vowel
        m+(iss)?(ippi) ) fizz;;   # matches "miss" or "mississippi" or others
        *              ) bazinga;; # catchall, matches anything not matched above
    esac
done

这篇关于如何在案例陈述中使用模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆