变量子串的语法介绍
name="Mrxujbing" #该变量的值,有索引是从0,1,2,3,4...
${变量} 返回变量值
${#name} 返回变量长度
${变量:start} 返回变量start数值之后的字符串,且包含start的数字(start值就是索引值)
${变量:start:length} 提取start之后的length限制的字符,例如${name:4:1}
${变量#word} 从变量开头删除最短匹配的word子串
${变量##word} 从变量开头删除最长匹配的word子串
${变量%word} 从变量结尾删除最短匹配的word
${变量%%word} 从变量结尾开始删除最长匹配的word
替换
${变量/pattern/string} 用string 代替第一个匹配的pattern
${变量//pattern/string} 用string 代替所有匹配的pattern
[root@localhost ~]# name="Mrxu160abcbbcacd"
[root@localhost ~]# echo ${name}
Mrxu160abcbbcacd
[root@localhost ~]# echo ${#name}
16
[root@localhost ~]# echo ${name:6}
0abcbbcacd
[root@localhost ~]# echo ${name:6:3}
0ab
实际练习
###截取字符串
[root@localhost ~]# echo $name
xujianbing
[root@localhost ~]# echo ${name:3:3}
ian
[root@localhost ~]# name2="abcABCabc123ABCabc"
[root@localhost ~]# echo ${name2#a*c}
ABCabc123ABCabc
[root@localhost ~]# echo ${name2##a*c} ###匹配最长的,就是全匹配,删晚了
[root@localhost ~]# echo ${name2%a*c}
abcABCabc123ABC
[root@localhost ~]# echo ${name2%%a*c}
[root@localhost ~]#
###用符号#有点难理解,从开头匹配,重点是开头的字符要对应;从结尾开始匹配重点是结尾的要匹配
[root@localhost ~]# echo ${name2%1*c} ###从结尾的
abcABCabc
[root@localhost ~]# echo ${name2#1*c}
abcABCabc123ABCabc
[root@localhost ~]# echo ${name2#a*3} ###从开头的
ABCabc
[root@localhost ~]# echo ${name2%a*3}
#####感觉直接用/替换成空更好理解
[root@localhost ~]# echo ${name2/ab/df}
dfcABCabc123ABCabc
[root@localhost ~]# echo ${name2//ab/df}
dfcABCdfc123ABCdfc
[root@localhost ~]# echo ${name2//abc/} ###将要截取的替换成空
ABC123ABC
[root@localhost ~]#
标签:子串,Shell,变量,echo,语法,name2,root,localhost,name
From: https://www.cnblogs.com/xjianbing/p/17752347.html