(4) Deletion and substitution of variable content

(1) Deletion of variables

[root@localhost scripts]# url=www.baidu.com.cn
[root@localhost scripts]# echo ${#url}     获取变量的长度
16
[root@localhost scripts]# echo ${url}       标准查看
www.baidu.com.cn
[root@localhost scripts]# echo ${url#*.}    从前往后,最短匹配
baidu.com.cn
[root@localhost scripts]# echo ${url##*.}   从前往后,最长匹配,贪婪匹配
cn
[root@localhost scripts]# url=www.baidu.com.cn
[root@localhost scripts]# echo ${url%.*}        从后往前,最短匹配
www.baidu.com
[root@localhost scripts]# echo ${url%%.*}       从后往前,最长匹配,贪婪匹配
www

(2) Variable index slice

[root@localhost scripts]# url=www.baidu.com.cn
[root@localhost scripts]# echo ${url:0:5}
www.b
[root@localhost scripts]# echo ${url:5:5}
aidu.
[root@localhost scripts]# echo ${url:5}
aidu.com.cn

(3) Replacement of variable content

[root@localhost scripts]# url=www.baidu.com.cn
[root@localhost scripts]# echo ${url/baidu/sina}
www.sina.com.cn
[root@localhost scripts]# echo ${url//w/N}      贪婪匹配
NNN.baidu.com.cn

(4) Substitution of variables

${变量名-新的变量值}
变量没有被赋值:会使用"新的变量值"替代
变量有被赋值(包括空值):不会被替代
[root@localhost scripts]# unset var1
[root@localhost scripts]# echo ${var1-aaaa}
aaaa
[root@localhost scripts]# var1=aaaa
[root@localhost scripts]# echo ${var1-bbbb}
aaaa
[root@localhost scripts]# var1=
[root@localhost scripts]# echo ${var1-bbbb}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324583209&siteId=291194637