每天三分半鐘搞定linux基礎知識(19) echo命令實現字串的擷取和替換

碼享客發表於2020-10-02

echo命令實現字串的擷取和替換

1 ## 號擷取,從右往左找第一個匹配的,從右往左刪

[aitian@aitian-CW65S ~]$ var=eaabbccddaa5
[aitian@aitian-CW65S ~]$ var2=`echo ${var##*aa}`
[aitian@aitian-CW65S ~]$ echo $var2
5

2 #號擷取,從右往左找最後一個匹配的,從右往左刪

[aitian@aitian-CW65S ~]$ var=eaabbccddaa5
[aitian@aitian-CW65S ~]$ var3=`echo ${var#*aa}`
[aitian@aitian-CW65S ~]$ echo $var3
bbccddaa5

3%%號擷取,從左往右找最後一個匹配的,從左往右刪

[aitian@aitian-CW65S ~]$ var=eaabbccddaa5
[aitian@aitian-CW65S ~]$ var4=`echo ${var%%aa*}`
[aitian@aitian-CW65S ~]$ echo $var4
e

4%號擷取,從左往右找第一個匹配的,從左往右刪

[aitian@aitian-CW65S ~]$ var=eaabbccddaa5
[aitian@aitian-CW65S ~]$ var5=`echo ${var%aa*}`
[aitian@aitian-CW65S ~]$ echo $var5
eaabbccdd

5擷取從左邊第幾個字元開始,及字元的個數

[aitian@aitian-CW65S ~]$ var=eaabbccddaa5
[aitian@aitian-CW65S ~]$ var6=`echo ${var:2:3}`
[aitian@aitian-CW65S ~]$ echo $var6
abb

6擷取從左邊第幾個字元開始,一直到末尾

[aitian@aitian-CW65S ~]$ var=eaabbccddaa5
[aitian@aitian-CW65S ~]$ var7=`echo ${var:3}`
[aitian@aitian-CW65S ~]$ echo $var7
bbccddaa5

7擷取從右邊第幾個字元開始,及字元的個數

[aitian@aitian-CW65S ~]$ var=eaabbccddaa5
[aitian@aitian-CW65S ~]$ var8=`echo ${var:0-3:2}`
[aitian@aitian-CW65S ~]$ echo $var8
aa

8擷取從右邊第幾個字元開始,一直到末尾

[aitian@aitian-CW65S ~]$ var=eaabbccddaa5
[aitian@aitian-CW65S ~]$ var9=`echo ${var:0-4}`
[aitian@aitian-CW65S ~]$ echo $var9
daa5

相關文章