标签:bash字符串操作
字符串操作之一:测试变量存在性
${varname:-word} | 如果varname存在且非null,返回其值,否则返回word |
${varname:=word} | 如果varname存在且非null,返回其值,否则将其设置为word,然后返回其值 |
${varname:?message} | 如果varname存在且非null,返回其值,否则打印varname:后跟message,并退出当前命令或脚本 |
${varname:+word} | 如果varname存在且非null,返回word,否则返回null |
${varname:offset} | 偏移offset个字符,取余下的所有字符 |
${varname:offset:length} | 偏移offset个字符,取length个字符 |
# echo ${age:-30} //变量age未设置,返回30 30 # age=28 # echo ${age:-30} //变量age设置为28,返回28 28 # name=king # echo ${name:=tom} //变量name已设置为king,故返回king king # unset name # echo ${name:=tom} //变量name被清空,未设置,则将变量name设置为tom tom # echo $name tom # echo ${sex:?"what‘s your sex?"} -bash: sex: what‘s your sex? //变量sex未设置显示what‘s your sex? # sex=female # echo ${sex:?"what‘s your sex?"} //变量sex已设置,显示female female # echo ${id:+"not null"} //变量id未设置,返回Null # id=100 # echo ${id:+"not null"} //变量id已设置,返回消息not null not null # echo ${msg:5} //偏移5个字符,取余下的所有字符 World # echo ${msg:5:2} //偏移5个字符,取两个字符 Wo
字符串操作之二:计算变量中的字符个数
${#varname}
# echo $msg HelloWorld # echo ${#msg} 10
字符串操作之三:使用模式和模式匹配来操作字符串
${varname#pattern} | 如果模式匹配变量取值的开头,删除最短的匹配部分,并返回其余部分 |
${varname##pattern} | 如果模式匹配变量取值的开头,删除最长的匹配部分,并返回其余部分 |
${varname%pattern} | 如果模式匹配变量取值的结尾,删除最短的匹配部分,并返回其余部分 |
${varname%%pattern} | 如果模式匹配变量取值的结尾,删除最长的匹配部分,并返回其余部分 |
${varname/pattern/string} | 用string替换第一个匹配pattern的部分 |
${varname//pattern/string} | 用string替换所有pattern匹配的部分 |
# Var=/etc/sysconfig/network-scripts/ifcfg-eth0 # echo $Var /etc/sysconfig/network-scripts/ifcfg-eth0 # echo ${Var#/*/} sysconfig/network-scripts/ifcfg-eth0 # echo ${Var##/*/} ifcfg-eth0 # Var=/home/yy/test.conf.bak # echo $Var /home/yy/test.conf.bak # echo ${Var%.*} /home/yy/test.conf # echo ${Var%%.*} /home/yy/test # echo $msg HelloWorld # echo ${msg/o/O} HellOWorld # echo ${msg//o/O} HellOWOrld
本文出自 “虎虎生威” 博客,请务必保留此出处http://tobeone.blog.51cto.com/817917/1557428
标签:bash字符串操作
原文地址:http://tobeone.blog.51cto.com/817917/1557428