1 字符串的截取
${字符串变量名:截取的开始下标} ,直到字符串最后。下标从1开始,空格也是一个字符串。原字符串不变
shiyanlou:~/ $ st="hello world shellgood" [22:22:59]
shiyanlou:~/ $ echo ${st:5} [22:28:06]
world shellgood
shiyanlou:~/ $ echo ${st:6} [22:28:25]
world shellgood
shiyanlou:~/ $ echo ${st:7} [22:28:35]
orld shellgood
shiyanlou:~/ $ echo $st [22:29:16]
hello world shellgood
shiyanlou:~/ $
${字符串变量名:开始的下标,需要截取的字符个数}
hiyanlou:~/ $ st2=${st:6:5} [22:33:07]
shiyanlou:~/ $ echo $st2 [22:33:19]
world
shiyanlou:~/ $ echo $st [22:33:22]
hello world shellgood
2 获取字符串的长度
${#字符串变量名}
shiyanlou:~/ $ echo ${#st} [22:33:38]
21
shiyanlou:~/ $
2 从头部开始去除
${字符串变量名#从头部开始需要去除的子串}
shiyanlou:~/ $ echo ${st#hel} 去除开始的子串hel [22:34:52]
lo world shellgood
shiyanlou:~/ $ echo ${st#*o} 去除从头开始到出现o的子串 [22:36:57]
world shellgood
shiyanlou:~/ $ echo ${st#*o } 去除从头开始到出现o空格的子串 [22:41:16]
world shellgood
shiyanlou:~/ $ echo ${st#*d} 去除从头开始到出现d的子串 [22:41:24]
shellgood
shiyanlou:~/ $ echo $st st内容不变 [22:41:59]
hello world shellgood
shiyanlou:~/ $ echo ${st#llo} llo子串不和头部匹配,不进行去除 [22:45:21]
hello world shellgood
shiyanlou:~/ $ echo ${st#world} world子串不和头部匹配,不进行去除 [22:45:30]
hello world shellgood
2.1 贪婪匹配
${字符串变量名##子串},如果子串匹配字符串的头部,一直要删除到最后一次
hello world shellgood
shiyanlou:~/ $ echo "${st##*o}" 去除最后一次出现o的位置 [22:45:53]
d
shiyanlou:~/ $
注意:使用括号括起来,表示一个整体,不容易出现误会和不可知的错误
3 从尾巴开始去除,%表示去尾巴,用法和去头相同
hiyanlou:~/ $ echo $st [22:56:15]
hello world shellgood
shiyanlou:~/ $ echo "${st%l*}" 从尾巴开始去除第一次出现l的位置 [23:03:29]
hello world shel
shiyanlou:~/ $ echo "${st%%l*}" 从尾巴开始去除最后一次出现l的位置 [23:03:54]
he
shiyanlou:~/ $ echo "${st%good}" 从尾巴开始匹配到good,进行去除 [23:04:03]
hello world shell
shiyanlou:~/ $ echo $st [23:04:26]
hello world shellgood
shiyanlou:~/ $
4 字符串的替换,原字符串内容不变
${字符串变量名/old子串/new子串},用new子串替换old子串
shiyanlou:~/ $ echo $st [23:04:26]
hello world shellgood
shiyanlou:~/ $ echo "${st/good/}" [23:04:32]
hello world shell
shiyanlou:~/ $ echo "${st/shell/}" [23:09:24]
hello world good
shiyanlou:~/ $ echo "${st/shell/java}" [23:09:39]
hello world javagood
shiyanlou:~/ $ echo $st [23:09:54]
hello world shellgood