shell变量的子串的删除/替换

${#string}
返回$string的长度

${string:position}
$string中,从$position位置之后开始提取子串

${string:position:length}
$string中,从$position位置之后开始提取$length长度的子串

[root@localhost SHELL]# NAME="ni hao, ming tian"
[root@localhost SHELL]# echo $NAME
ni 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 $NAME
abcABC123ABCabcde
[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 $NAME
abcABC123ABCabc
[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 $NAME
I am a student student
[root@localhost SHELL]# 

你可能感兴趣的:(shell)