Shell字符串
字符串的定义
str1=hello
str2='hello'
str3="hello"
字符串长度的获取
${#string_name}
字符串的拼接
直接将两个字符串放在一起即可:
str1=hello
str2=shell
str3=$str1$str2
str4="$str1$str2"
str5="${str1}:${str2}"
字符串的截取
(1)从左开始计数,截取方向从左往右(从0开始计数,string是被截取的字符串,start是开始截取的位置,length是截取的长度)
${string:start:length}
(2)从右开始计数,截取方向从左往右(从1开始计数,string是被截取的字符串,start是开始截取的位置,length是截取的长度)
${string:0-start:length}
代码示例
#!/bin/bash
#字符串的定义
str1=hello
str2='hello world'
str3="hello shell!"
#字符串长度的获取
echo str1:${#str1}
echo str2:${#str2}
echo str3:${#str3}
#字符串的拼接
str4=$str1$str2
str5="$str1$str2"
str6="${str1}:${str2}"
echo str4:$str4
echo str5:$str5
echo str6:$str6
#字符串的截取
str7=${str2:1:5}
str8=${str3:0-10:5}
echo str7:$str7
echo str8:$str8
输出结果
str1:5
str2:11
str3:12
str4:hellohello world
str5:hellohello world
str6:hello:hello world
str7:ello
str8:llo s