码迷,mamicode.com
首页 > 系统相关 > 详细

Shell中的${}、##和%%几点说明

时间:2017-12-25 21:26:58      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:shel %% ##

假设我们定义了一个变量为:

复制代码 代码如下:


file=/dir1/dir2/dir3/my.file.txt


可以用${ }分别替换得到不同的值:

复制代码 代码如下:


${file#*/}:删掉第一个 / 及其左边的字符串:dir1/dir2/dir3/my.file.txt
${file##*/}:删掉最后一个 /  及其左边的字符串:my.file.txt
${file#*.}:删掉第一个 .  及其左边的字符串:file.txt
${file##*.}:删掉最后一个 .  及其左边的字符串:txt
${file%/*}:删掉最后一个  /  及其右边的字符串:/dir1/dir2/dir3
${file%%/*}:删掉第一个 /  及其右边的字符串:(空值)
${file%.*}:删掉最后一个  .  及其右边的字符串:/dir1/dir2/dir3/my.file
${file%%.*}:删掉第一个  .   及其右边的字符串:/dir1/dir2/dir3/my


记忆的方法为:

复制代码 代码如下:


# 是 去掉左边(键盘上#在 $ 的左边)
%是去掉右边(键盘上% 在$ 的右边)
单一符号是最小匹配;两个符号是最大匹配
${file:0:5}:提取最左边的 5 个字节:/dir1
${file:5:5}:提取第 5 个字节右边的连续5个字节:/dir2


也可以对变量值里的字符串作替换:

复制代码 代码如下:


${file/dir/path}:将第一个dir 替换为path:/path1/dir2/dir3/my.file.txt
${file//dir/path}:将全部dir 替换为 path:/path1/path2/path3/my.file.txt



(2)

    ## #后面如果直接跟匹配的字符串,会删除前面的或者左边的所有字符串,主要通配符的位置(# ## *必须在前面比如*llo);跟完整字符串只匹配第一个,效果一样,如果完整字符串不是第一个,原样输出

    %% %后面如果直接跟匹配的字符串,会删除前面的或者右边边的所有字符串,主要通配符的位置(% %% *必须在在后面比如he*),跟完整字符串原样输出

比如

a=" this is hello  a maomaochong hello this!"

 35 #echo ${a#hello} //this is hello  a maomaochong hello this!

 36 #echo ${a##hello}//this is hello  a maomaochong hello this!

 37 #echo ${a#*llo} //a maomaochong hello this!

 38 #echo ${a##*llo} //this !

 39 echo ${a%this}//this is hello  a maomaochong hello this!

 40 echo ${a%%this}//this is hello  a maomaochong hello this!

 41 #echo ${a%he*} //   this is hello  a maomaochong                                                                                              

 42 #echo ${a%%he*}//this is 

//

Shell中的${}、##和%%几点说明

标签:shel %% ##

原文地址:http://blog.51cto.com/13375232/2054548

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!