参数替换中的模式匹配
# 和## 从字符串的左边开始,并且去掉左边的字符串,
% 和 %% 从字符串的右边开始,并且去掉右边的子串.
例如
name=hello lhhs "root"
name=${name#‘"‘}; name=${name%‘"‘}
结果为root
################################Start Script#######################################
1 #!/bin/bash
2 # patt-matching.sh
3
4 # 使用# ## % %%来进行参数替换操作的模式匹配.
5
6 var1=abcd12345abc6789
7 pattern1=a*c # * (通配符) 匹配a - c之间的任何字符.
8
9 echo
10 echo "var1 = $var1" # abcd12345abc6789
11 echo "var1 = ${var1}" # abcd12345abc6789
12 # (alternate form)
13 echo "Number of characters in ${var1} = ${#var1}"
14 echo
15
16 echo "pattern1 = $pattern1" # a*c (everything between ‘a‘ and ‘c‘)
17 echo "--------------"
18 echo ‘${var1#$pattern1} =‘ "${var1#$pattern1}" # d12345abc6789
19 # 最短的可能匹配, 去掉abcd12345abc6789的前3个字符
20 # |-| ^^^
21 echo ‘${var1##$pattern1} =‘ "${var1##$pattern1}" # 6789
22 # 最远的匹配,去掉abcd12345abc6789的前12个字符.
23 # |----------| ^^^^
24
25 echo; echo; echo
26
27 pattern2=b*9 # ‘b‘ 到‘9‘之间的任何字符
28 echo "var1 = $var1" # 还是 abcd12345abc6789
29 echo
30 echo "pattern2 = $pattern2"
31 echo "--------------"
32 echo ‘${var1%pattern2} =‘ "${var1%$pattern2}" # abcd12345a
33 # 最近的匹配, 去掉abcd12345abc6789的最后6个字符
34 # |----| ^^^^
35 echo ‘${var1%%pattern2} =‘ "${var1%%$pattern2}" # a
36 # 最远匹配, 去掉abcd12345abc6789的最后12个字符
37 # |-------------| ^^^^^^
38
39 # 记住, # 和## 从字符串的左边开始,并且去掉左边的字符串,
40 # % 和 %% 从字符串的右边开始,并且去掉右边的子串.
41
42 echo
43
44 exit 0