操作字符串之提取字串-1-${string:position:length}

在Linux系统中,Bash所支持的字符串操作的语法/工具数量特别多,但是这些操作的语法/工具没有统一的标准,一些字符串操作是参数替换的子集,另外一些是使用expr命令。

本次为讲解的是参数替换字符串操作,有兴趣的人可以自行了解expr字符串替换的用法,个人认为,方法只是用来解决问题的,掌握一种简单快捷的字符串替换的用法即可。

1.${string:position:length}

在string中从位置position开始提取length长度的子串。

2.实例

操作字符串样例:string=abc123ABC456xyz

             索引下标从0开始 0123456789...........

字符串操作默认从左边开始进行

2.1.提取全部string字符串

命令:

echo ${string:0}

[root@rhel77 ~]# string=abc123ABC456xyz
[root@rhel77 ~]# echo ${string:0}
abc123ABC456xyz
[root@rhel77 ~]# 

2.2.从第7位开始,提取string剩余子串

命令:

echo ${string:7}

[root@rhel77 ~]# echo ${string:7}
BC456xyz
[root@rhel77 ~]# 

2.3.从第7位开始,提取长度为3的string子串

echo ${string:7:3}

[root@rhel77 ~]# echo ${string:7:3}
BC4
[root@rhel77 ~]# 

2.4.从string的右边开始提取长度为4的子串

使用圆括号()或者使用一个空格“转义”位置参数,可以实现string从右边开始提取子串

命令:

echo ${string:(-4)}

OR

echo ${string: -4}

[root@rhel77 ~]# echo ${string:(-4)}
6xyz
[root@rhel77 ~]# 
[root@rhel77 ~]# echo ${string: -4}
6xyz
[root@rhel77 ~]# 

你可能感兴趣的:(linux字符串,bash,开发语言)