bash提取字符串${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 ~]#

到此这篇关于bash提取字符串${string:position:length}的具体使用的文章就介绍到这了,更多相关bash提取字符串内容请搜索aitechtogether.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持aitechtogether.com!

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
社会演员多的头像社会演员多普通用户
上一篇 2023年12月27日
下一篇 2023年12月27日

相关推荐

此站出售,如需请站内私信或者邮箱!