多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] # shell中变量子字符串的常用操作 |id|表达式|说明| |-|-|-| |1|${#string}|返回$string的长度| |2|${string:position}|在$string中,从$position之后开始提取子字符串| |3|${string:position:length}|在$string中,从位置$position之后开始提取长度为$length的子串| |4|${string#substring}|从变量$string开头开始删除最短匹配$substring子字符串| |5|${string##substring}|从变量$string开头开始删除最长匹配$substring子字符串| |6|${string%substring}|从变量$string结尾开始删除最短匹配$substring子字符串| |7|${string%%substring}|从变量$string结尾开始删除最长匹配$substring子字符串| |8|${string/substring/replace}|使用$replace,来替代第一个匹配$substring| |9|${string/#substring/replace}|如果$string前缀匹配$substring,就用$replace来代替匹配$substring| |10|${string/%substring/replace}|如果$string后缀匹配$substring,就用$replace来代替匹配$substring| ## 举例说明 首先,定义变量`PHPER=“hello world”`, ~~~ [luo@LNMP-CenOS-6.5 ~] $ PHPER="hello world" [luo@LNMP-CenOS-6.5 ~] $ echo ${PHPER} hello world ~~~ ### 返回变量PHPER的值长度 ~~~ [luo@LNMP-CenOS-6.5 ~] $ echo ${#PHPER} 11 ~~~ ### 截取变量值从第2个字符之后开始取,默认取后面字符的全部(第二个字符串不包含在内) ~~~ [luo@LNMP-CenOS-6.5 ~] $ echo ${PHPER:2} llo world ~~~ ### 截取PHPER变量字符串从第2个字符之后开始,取两个字符 ~~~ [luo@LNMP-CenOS-6.5 ~] $ echo ${PHPER:2:2} ll ~~~ ### 从变量开头删除子字符串 ~~~ [luo@LNMP-CenOS-6.5 ~] $ echo ${PHPER#hello} world ~~~ ### 从变量最后开始匹配子字符串并删除 ~~~ [luo@LNMP-CenOS-6.5 ~] $ echo ${PHPER%ld} hello wor ~~~ ### 从变量结尾开始删除最长匹配子字符串 ~~~ [luo@LNMP-CenOS-6.5 ~] $ echo ${PHPER%%o world} hell ~~~ ### 使用特定字符串代替第一个匹配到的字符串 ~~~ [luo@LNMP-CenOS-6.5 ~] $ echo ${PHPER/hello/hi} hi world ~~~ ### 使用特定字符串替代从变量结尾开始匹配的子字符串 ~~~ [luo@LNMP-CenOS-6.5 ~] $ echo ${PHPER/%world/beijing} hello beijing ~~~ ### 使用特定字符串替代从变量开头开始匹配的字符串 ~~~ [luo@LNMP-CenOS-6.5 ~] $ echo ${PHPER/#hello/hi} hi world ~~~