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

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值