Bash的参数扩展(Parameter Expansion)以$开头,我们常见的就是${var}这样的形式,这表示将名为var的变量的内容在这里进行替换扩展。这里的参数,其实就是我们说的变量。其实,Bash的参数扩展还有更丰富更复杂的形式,基本思路就是将名为var的变量的全部或者某一部分替换出来。
本文争取说清楚##和%%这两种扩展的用法。
${parameter#word}
${parameter##word}
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.
word是一个pattern,这个pattern简单说,就是主要有*,?,[...]这三种形式的
#表示从前匹配,并且按照最短路劲的模式匹配;
##表示从前匹配,并且按照最长路劲的模式匹配;
匹配之后,将匹配到的字符串删除,留下剩下的,用来进行Bash的参数扩展。下面举例:
[xinlin@ifos ~]$ str=https://www.maixj.net/xiaowuzhi
[xinlin@ifos ~]$ echo "test string is : $str"
test string is : https://www.maixj.net/xiaowuzhi
[xinlin@ifos ~]$ echo ${str#*/} # 从前面开始,找到第一个/符号
/www.maixj.net/xiaowuzhi
[xinlin@ifos ~]$ echo ${str##*/} # 从前面开始,找到最后一个/符号
xiaowuzhi
${parameter%word}
${parameter%%word}
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.
%%基本跟##一样,只是从后面开始匹配和截取。直接举例吧:
[xinlin@ifos ~]$ echo "test string is : $str"
test string is : https://www.maixj.net/xiaowuzhi
[xinlin@ifos ~]$ echo ${str%/*} # 从后面开始匹配,找到第一个/符号
https://www.maixj.net
[xinlin@ifos ~]$ echo ${str%%/*} # 从后面开始匹配,找到最后一个/符号
http:
以上就是对Bash参数扩展中,##和%%用法的简单介绍。这两个操作在截取路径或url字符串的某些前面部分或者某些后面部分时,非常有用。
再补充几个例子:
[xinlin@ifos ~]$ echo ${str##*z}
hi
[xinlin@ifos ~]$ echo ${str%%/[x]*}
https://www.maixj.net
[xinlin@ifos ~]$ echo ${str##*[w]*ne?}
/xiaowuzhi