分享 | 交流
让学习成为一种习惯

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

${string#substring}
从变量$string开头开始删除最短匹配$substring子串

${string##substring}
从变量$string开头开始删除最长匹配$sunstring子串

[root@localhost SHELL]# echo $NAME
abcABC123ABCabcde
[root@localhost SHELL]# echo ${NAME#a*C}
123ABCabcde
[root@localhost SHELL]# echo ${NAME##a*C}
abcde

${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

注意:在进行#或##匹配时,$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变量子串知识及示例

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

留时刻 - Linux系统教程,运维经验分享

加入我们给我留言