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

转自:https://www.cnblogs.com/Template/p/9079470.html

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

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

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: -1}: 打印最后一个字符

复制代码

记忆的方法为:
#是 去掉左边(键盘上#在 $ 的左边)
%  是去掉右边(键盘上% 在$ 的右边)
单一符号是非贪婪匹配;两个符号是贪婪匹配

${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 there’s an assignement to bar

复制代码

man bash :

${parameter:-word}
Use Default Values. If parameter is unset or null, the expansion of word is substituted. Otherwise,
the value of parameter is substituted.
${parameter:=word}
Assign Default Values. If parameter is unset or null, the expansion of word is assigned to parameter.
The value of parameter is then substituted. Positional parameters and special parameters may not be
assigned to in this way.
${parameter:?word}
Display Error if Null or Unset. If parameter is null or unset, the expansion of word (or a message to
that effect if word is not present) is written to the standard error and the shell, if it is not inter-
active, exits. Otherwise, the value of parameter is substituted.
${parameter:+word}
Use Alternate Value. If parameter is null or unset, nothing is substituted, otherwise the expansion of
word is substituted.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值