首页 » 信息技术 »

Bash参数扩展中##和%%的用法

2019年2月19日 / 99次阅读
Shell

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简单说,就是主要有*,?,[...]这三种形式的glob通配符表达式

#表示从前匹配,并且按照最短路劲的模式匹配;

##表示从前匹配,并且按照最长路劲的模式匹配;

匹配之后,将匹配到的字符串删除,留下剩下的,用来进行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

本文链接:https://www.maixj.net/ict/bash-hash-20227

相关文章

留言区


前一篇:
后一篇:

栏目精选

云上小悟,麦新杰的独立博客

Ctrl+D 收藏本页

栏目


©Copyright 麦新杰 Since 2014 云上小悟独立博客版权所有 备案号:苏ICP备14045477号-1。云上小悟网站部分内容来源于网络,转载目的是为了整合信息,收藏学习,服务大家,有些转载内容也难以判断是否有侵权问题,如果侵犯了您的权益,请及时联系站长,我会立即删除。

网站二维码
go to top