${#string}
返回$string的長度
${string:position}
在$string中,從$position位置之後開始提取子串
${string:position:length}
在$string中,從$position位置之後開始提取$length長度的子串
[root@localhost SHELL]# NAME="ni hao, ming tian"[root@localhost SHELL]# echo $NAMEni hao, ming tian[root@localhost SHELL]# echo ${NAME}ni hao, ming tian[root@localhost SHELL]# echo ${#NAME}17[root@localhost SHELL]# echo ${NAME:3}hao, ming tian[root@localhost SHELL]# echo ${NAME:3:6}hao, m[root@localhost SHELL]#
${string#substring}
從變數$string開頭開始刪除最短匹配$substring子串
${string##substring}
從變數$string開頭開始刪除最長相符$sunstring子串
e[root@localhost SHELL]# echo $NAMEabcABC123ABCabcde[root@localhost SHELL]# echo ${NAME#a*C}123ABCabcde[root@localhost SHELL]# echo ${NAME##a*C}abcde[root@localhost SHELL]#
${string%substring}
從變數$string結尾開始刪除最短匹配$substring子串
${string%%substring}
從變數$string結尾開始刪除最長相符$substring子串
[root@localhost SHELL]# NAME=abcABC123ABCabc[root@localhost SHELL]# echo $NAMEabcABC123ABCabc[root@localhost SHELL]# echo ${NAME%%a*c}[root@localhost SHELL]# echo ${NAME%a*c}abcABC123ABC[root@localhost SHELL]# echo ${NAME#b*c}abcABC123ABCabc[root@localhost SHELL]# echo ${NAME#bc}abcABC123ABCabc[root@localhost SHELL]# echo ${NAME%bc}abcABC123ABCa[root@localhost SHELL]# echo ${NAME%%bc}abcABC123ABCa[root@localhost SHELL]# echo ${NAME%C*c}abcABC123AB[root@localhost SHELL]# echo ${NAME%%C*c}abcAB[root@localhost SHELL]# echo ${NAME%%C*b}abcABC123ABCabc[root@localhost SHELL]# echo ${NAME}abcABC123ABCabc[root@localhost SHELL]#
注意:在進行#或##匹配時,$string的首字元必須是被刪除子串$substring的第一個字元,不然無法匹配刪除;
在進行%或者%%匹配時,$string的最後一個字元必須是被刪除子串$substring的最後一個字元,不然無法進行刪除操作;
${parameter/parttern/string}
用string來替換第一個匹配的pattern
${parameter/#parttern/string}
從開頭匹配parameter變數中的pattern,匹配上後就用string來替換匹配的pattern
${parameter/%pattern/string}
從結尾開始匹配parameter變數中的pattern,匹配上後就用string替換匹配的pattern
${parameter//pattern/string}
用string來替換parameter變數中所有匹配的pattern
[root@localhost SHELL]# NAME="I am a student student"[root@localhost SHELL]# echo ${NAME//student/teacher}I am a teacher teacher[root@localhost SHELL]# echo ${NAME/#student/teacher}I am a student student[root@localhost SHELL]# echo ${NAME/%student/teacher}I am a student teacher[root@localhost SHELL]# echo ${NAME/%I am /teacher}I am a student student[root@localhost SHELL]# echo ${NAME/#I am /teacher}teachera student student[root@localhost SHELL]# echo ${NAME/#I am a/teacher}teacher student student[root@localhost SHELL]# echo $NAMEI am a student student[root@localhost SHELL]#