shell中的${},##和%%的使用

文章转自:https://blog.csdn.net/yiyecheer/article/details/53385012

 

以下是理解:

#!/bin/bash

string="this is a test string."
file="/dir1/dir2/dir3/my.file.txt"

echo ${string} #this is a test string.
echo "${string%st*}" #this is a test 
echo ${string%%st*} #this is a te
echo ""
echo ${string} #this is a test string.
echo "${string#*st}" # string.
echo ${string##*st} #ring. 


echo "==========================="

echo ${file} #/dir1/dir2/dir3/my.file.txt
echo ${file%dir*} #/dir1/dir2/
echo ${file%%dir*} #/
echo ""
echo ${file} #/dir1/dir2/dir3/my.file.txt
echo ${file#*dir} #1/dir2/dir3/my.file.txt
echo ${file##*dir} #3/my.file.txt

注:echo 后的注释表示预计输出

在提取字符时%,%%,#,##到底什么时候使用呢?记起来相对麻烦。

其实,在提取规则中,可以发现一个特殊的字符 “ * ”,在shell通配符中代表比配“全部”

所以我们其实可以这么理解:

0.%删右边,#删左边(其实也可以从*和% / #的位置可以知道是删除左边还是右边)

1.%和%%以及#和##,越长删的越多(%%比%长)

2.%st*:可以表示为st之后的全部(*),那个st?只有一个%:所以是需要删除最少的那个st咯,所以综合下来%st*表示为删除掉st之后(右边)比配到的全部(*)的最少(%)的部分,其他类似。说白了,%st*就是表示删除掉比配到的st(包含)之后全部内容,这个内容删的越少越好,同理##*dir就表示删除比配到的dir(包含)之前的内容全部内容,这个内容删的越多越好

输出结果:

this is a test string.
this is a test 
this is a te

this is a test string.
 string.
ring.
===========================
/dir1/dir2/dir3/my.file.txt
/dir1/dir2/
/

/dir1/dir2/dir3/my.file.txt
1/dir2/dir3/my.file.txt
3/my.file.txt

嗯嗯嗯,大概就是这么理解了,-_-||,解释起来比写bug还难,将就着知道意思就行了

更多详细内容查看:

文章转自:https://blog.csdn.net/yiyecheer/article/details/53385012

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值