在我们的shell 编程中,一个必不可少的操作就是针对于字符串的操作,
重要有字符串替换,计算字符串长度 等等。。。
原文地址:
https://blog.csdn.net/github_33736971/article/details/53980123
下面对这些操作进行一个总结。
${#string}
返回$string的长度
${string:position}
在$string中,从$position位置之后开始提取子串
${string:position:length}
在$string中,从$position位置之后开始提取$length长度的子串
[root@localhost SHELL]
[root@localhost SHELL]
ni hao,ming tian
[root@localhost SHELL]
ni hao,ming tian
[root@localhost SHELL]
17
[root@localhost SHELL]
hao,ming tian
[root@localhost SHELL]
hao,m
[root@localhost SHELL]
${string#substring}
从变量$string开头开始删除最短匹配$substring子串
${string##substring}
从变量$string开头开始删除最长匹配$sunstring子串
[root@localhost SHELL]
[root@localhost SHELL]
abcABC123ABCabcde
[root@localhost SHELL]
123ABCabcde
[root@localhost SHELL]
abcde
[root@localhost SHELL]
- ${string%substring}
从变量$string结尾开始删除最短匹配$substring子串
${string%%substring}
从变量$string结尾开始删除最长匹配$substring子串
[root@localhost SHELL]
[root@localhost SHELL]
abcABC123ABCabc
[root@localhost SHELL]
[root@localhost SHELL]
abcABC123ABC
[root@localhost SHELL]
abcABC123ABCabc
[root@localhost SHELL]
abcABC123ABCabc
[root@localhost SHELL]
abcABC123ABCa
[root@localhost SHELL]
abcABC123ABCa
[root@localhost SHELL]
abcABC123AB
[root@localhost SHELL]
abcAB
[root@localhost SHELL]
abcABC123ABCabc
[root@localhost SHELL]
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]
[root@localhost SHELL]
I am a teacher teacher
[root@localhost SHELL]
I am a student student
[root@localhost SHELL]
I am a student teacher
[root@localhost SHELL]
I am a student student
[root@localhost SHELL]
teachera student student
[root@localhost SHELL]
teacher student student
[root@localhost SHELL]
I am a student student
[root@localhost SHELL]