字符串是shell编程中最常用最有用的数据类型(shell编程中基本也就数字和字符串),字符串可以用单引号,也可以用双引号,也可以不用引号。关于三者的使用和区别请参考
1.获取字符串长度
[robot@hadoop103 ~]$ string="abcd"
[robot@hadoop103 ~]$ echo ${string} #同样用$去变量的值,打印
abcd
[robot@hadoop103 ~]$ echo ${#string} #只是在取变量值$,在变量的前面加了#,则$#取的是变量值。
4
2.获取字符串的子串
[robot@hadoop103 ~]$ string="hello world, this is xiaoming"
[robot@hadoop103 ~]$ echo ${string:1:3} #
ell
[robot@hadoop103 ~]$ echo ${string:2:3} #
llo
[robot@hadoop103 ~]$ echo ${string:0:3} #
hel
[robot@hadoop103 ~]$ echo ${string:0:6} #
hello
[robot@hadoop103 ~]$ echo ${string:0:7} #
hello w
[robot@hadoop103 ~]$
3.拼接字符串
[robot@hadoop103 ~]$ str1=$str "," 'beijing'
bash: ,: command not found...
[robot@hadoop103 ~]$ str="hello world"
[robot@hadoop103 ~]$ str1="$str,beijing,${str}"
[robot@hadoop103 ~]$ echo $str1
hello world,beijing,hello world
4.获取字符串中子串的位置
[robot@hadoop103 ~]$ str="abcdefgshi jdfd"
[robot@hadoop103 ~]$ echo `expr index "$str" f` #用了双引号,如果存在返回子串的真实位置,角标从1开始计算。
6
[robot@hadoop103 ~]$ echo `expr index "$str" sh`
8
[robot@hadoop103 ~]$ echo `expr index "$str" dd` #获取一个不存在的子串位置,不会报错,而是返回该串中最小字符在字符串中首次位置。
4
[robot@hadoop103 ~]$ echo `expr index "$str" ddsss`
4
[robot@hadoop103 ~]$ echo `expr index "$str" hddsss`
4
[robot@hadoop103 ~]$ echo `expr index "$str" hddsss`
4
[robot@hadoop103 ~]$ echo `expr index "$str" hef`
5
[robot@hadoop103 ~]$ echo `expr index "$str" hefa`
1