Bash中的模式匹配 [英] pattern matching in Bash
问题描述
这里是获取文件名不同部分的示例
Here is an example to get different parts of a filename
bash-3.2$ pathandfile=/tmp/ff.txt
bash-3.2$ filename=$(basename $pathandfile)
bash-3.2$ echo $filename
ff.txt
bash-3.2$ echo ${filename##*.}
txt
bash-3.2$ echo ${filename%.*}
ff
我想知道##和%在模式中是什么意思.彭定康匹配如何工作?
I was wondering what does ## and % mean in the patterns. How is the patten matching working?
感谢和问候!
推荐答案
bash
的联机帮助页说:
$ {parameter#word}
$ {parameter ## word}
${parameter#word}
${parameter##word}
删除匹配的前缀模式.单词被扩展以产生一个模式,就像在路径名扩展中.如果模式与parameter的值的开头匹配,则扩展的结果是使用最短的匹配模式(
#
情况)或最长的匹配模式(##
大小写).如果参数为@
或*
,则模式删除操作为依次将其应用于每个位置参数,展开即为结果列表.如果parameter是一个用@
或*
下标的数组变量,则该模式删除操作依次应用于数组的每个成员,并且扩展是结果列表.
Remove matching prefix pattern. The word is expanded to produce a pattern just as in pathname expansion. If the pattern matches the beginning of the value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the
#
case) or the longest matching pattern (the##
case) deleted. If parameter is@
or*
, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with@
or*
, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.
$ {parameter%word}
$ {parameter %% word}
${parameter%word}
${parameter%%word}
删除匹配的后缀模式.单词被扩展以生成模式,就像在路径名扩展中.如果该模式与扩展后的尾部匹配参数的值,则扩展的结果是的扩展值具有最短匹配模式(
%
大小写)或最长匹配模式(%%
大小写)的参数.如果参数是@
或*
,则模式删除依次将运算应用于每个位置参数,展开为结果列表.如果parameter是一个用@
或*
下标的数组变量,则模式删除操作依次应用于数组的每个成员,并且扩展就是结果列表.
Remove matching suffix pattern. The word is expanded to produce a pattern just as in pathname expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the
%
case) or the longest matching pattern (the%%
case) deleted. If parameter is@
or*
, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with@
or*
, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.
这篇关于Bash中的模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!