版权声明:转载或者应用请注明出处 https://blog.csdn.net/qq_35180983/article/details/82501416
字符串是shell编程中最常用最有用的数据类型(除了数字和字符串,也没有其它类型好用),字符串可以用单引号,也可以用双引号,也可以不用引号。
1、单引号
str='this is a string'
[root@hadoop01 shell]# vi String.sh
#!/bin/bash
str1='this is a String'
echo $str1
[root@hadoop01 shell]# chmod a+x ./String.sh
[root@hadoop01 shell]# ./String.sh
this is a String
注意:
- 单引号里的任何字符都会原样输出,单引号字符串中的变量是无效的;
- 单引号字串中不能出现单引号(对单引号使用转义符后也不行)
2、双引号
[root@hadoop01 shell]# vi String.sh
#!/bin/bash
str1='this is a String'
str2="look at:\"$str1\"!\n"
echo $str1
echo $str2
[root@hadoop01 shell]# ./String.sh
this is a String
look at:"this is a String"!\n
双引号的优点:
- 双引号里可以有变量
- 双引号里可以出现转义字符
3、拼接字符串
[root@hadoop01 shell]# vi String.sh
#!/bin/bash
str1='this is a String'
str="hello,$str1!"
echo $str
[root@hadoop01 shell]# ./String.sh
hello,this is a String!
4、获取字符串长度
string="abcdef"
echo ${#string} #输出 6
[root@hadoop01 shell]# vi String.sh
#!/bin/bash
string="abcdef"
echo ${#string}
[root@hadoop01 shell]# ./String.sh
6
5、提取子字符串
以下实例从字符串第 2 个字符开始截取 4 个字符:
string="this is a class"
echo ${string:1:4} # 输出 his
[root@hadoop01 shell]# vi String.sh
#!/bin/bash
string="this is a class"
echo ${string:1:4}
[root@hadoop01 shell]# ./String.sh
his
6、查找子字符串
查找字符 "i 或 s" 的位置:
string="this is a class"
echo `expr index "$string" is` #输出 3 (注意""不能去掉)
[root@hadoop01 shell]# vi String.sh
#!/bin/bash
string="this is a class"
echo `expr index "$string" is`
[root@hadoop01 shell]# ./String.sh
3
注意:
之上脚本中 " ` " 是反引号,而不是单引号 " ' ",不要看错了哦。反引号`` 某些时候可用$()来替代。
如:echo `ll` 等价于 echo $(ll)