在本文中,将简单地介绍Shell Script中一些使用替换(substitution)操作进行的字符串的操作,例如获取字符串的长度、获取字符串子串、移除字符串中指定部分以及替换字符串中指定部分等操作。
获取字符串长度
使用${#string}
可以得到对应字符串的长度,其等同于C语言中的strlen()
函数。
$ greeting="hello world"
$ echo ${#greeting}
11
获取字符串子串
使用${string:position}
或${string:position:length}
可以用于获取字符串的子串,其中position
为以0为基准的字符串字符位置。
使用${string:position}
将获取从position
指定位置开始的子串,例如示例中的${greeting:6}
将获取从第七个字符开始的子串'world'
。
使用${string:position:length}
将获取从position
指定位置开始的长度为length
的子串,例如示例中的${greeting:0:5}
将获取从第一个字符开始的长度为5的子串'hello'
。
$ greeting="hello world"
$ echo ${greeting:6}
world
$