文章转自: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还难,将就着知道意思就行了
更多详细内容查看: