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

Shell中的${}、##和%%使用范例

时间:2018-05-23 22:12:27      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:fine   some   txt   new   sig   贪婪   assign   variable   form   

假设定义了一个变量为,代码如下:

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

[root@localhost ~]# p=123abc
[root@localhost ~]# echo ${p//[0-9]/}      #将变量中的数字替换为空
abc

+----------------------------------------------------------------------+
|Form Meaning
+----------------------------------------------------------------------+
|${variable:?word} Complain if undefined or null
|${variable:-word} Use new value if undefined or null
|${variable:+word} Opposite of the above
|${variable:=word} Use new value if undefined or null, and redefine.
+----------------------------------------------------------------------+

foo=${bar:-something}

echo $foo # something
echo $bar # no assignement to bar, bar is still empty

foo=${bar:=something}

echo $foo # something
echo $bar # something too, as theres an assignement to bar

 

 

Shell中的${}、##和%%使用范例

标签:fine   some   txt   new   sig   贪婪   assign   variable   form   

原文地址:https://www.cnblogs.com/Template/p/9079470.html

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