bash 如何在case语句中使用模式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4554718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use patterns in a case statement?
提问by Ramiro Rela
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:
该man
页面说case
语句使用“文件名扩展模式匹配”。
我通常想要一些参数的短名称,所以我去:
case in
req|reqs|requirements) TASK="Functional Requirements";;
met|meet|meetings) TASK="Meetings with the client";;
esac
logTimeSpentIn "$TASK"
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.
我尝试了类似req*
或me{e,}t
我理解的模式可以正确扩展以匹配文件名扩展上下文中的这些值,但它不起作用。
回答by Paused until further notice.
Brace expansion doesn't work, but *
, ?
and []
do. If you set shopt -s extglob
then you can also use extended pattern matching:
大括号扩展不起作用,但是*
,?
和[]
做。如果设置,shopt -s extglob
则还可以使用扩展模式匹配:
?()
- 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
?()
- 模式出现零次或一次*()
- 零次或多次出现的模式+()
- 出现一次或多次模式@()
- 出现一次模式!()
- 除了图案之外的任何东西
Here's an example:
下面是一个例子:
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
回答by plundra
I don't think you can use braces.
我不认为你可以使用大括号。
According to the Bash manual about case in Conditional Constructs.
根据 Bash 手册关于Conditional Constructs 中的case 。
Each patternundergoes tilde expansion, parameter expansion, command substitution, and arithmetic expansion.
每个模式都经历波浪号扩展、参数扩展、命令替换和算术扩展。
Nothing about Brace Expansionunfortunately.
不幸的是,没有关于支撑扩展的内容。
So you'd have to do something like this:
所以你必须做这样的事情:
case in
req*)
...
;;
met*|meet*)
...
;;
*)
# You should have a default one too.
esac