Shell - 字符串

(1)单引号

str='this is a string'

注意:
单引号里的任何字符都会原样输出,单引号字符串中的变量是无效的;
单引号字串中不能出现单引号(对单引号使用转义符后也不行)。

(2)双引号

class='1234A'
str="this is \"$class\"! \n"

双引号的优点:
双引号里可以有变量
双引号里可以出现转义字符

(3)拼接字符串

your_name="haha"
greeting="hello, $your_name !"
echo greeting

(4)获取字符串长度

string="abcdef"
echo ${#string} #输出 6

(5)提取子字符串

#以下实例从字符串第 2 个字符开始截取 4 个字符:
string="this is 1511A class"
echo ${string:1:4} #输出 his

(6)查找子字符串

#查找字符 "i 或 s" 的位置:
string="this is 1511A class"
echo `expr index "$string" is`  #输出 3  (注意""不能去掉) 

注意: 以上脚本中 “`” 是反引号,而不是单引号 “’”
反引号` 某些时候可用$()来替代。如:echo `ll` 等价于 echo $(ll)

发布了544 篇原创文章 · 获赞 289 · 访问量 23万+

猜你喜欢

转载自blog.csdn.net/BlessingXRY/article/details/100177625