shell编程系列1--shell脚本中的变量替换 变量替换总结: 1、${变量#匹配规则} # 从头开始匹配,最短删除 2、${变量##匹配规则} # 从头开始匹配,最长删除(贪婪模式) 3、${变量%匹配规则} # 从尾开始匹配,最短删除 4、${变量%%匹配规则} # 从尾开始匹配,最长删除(贪婪模式) 5、${变量/旧字符串/新字符串} # 替换变量内的旧字符串为新字符串,只替换第一个 6、${变量//旧字符串/新字符串} # 替换变量内的旧字符串为新字符串,全部替换 variable_1="i love you,do you love me" 举例: [root@localhost ~]# variable_1="i love you,do you love me" [root@localhost ~]# echo $variable_1 i love you,do you love me # 从头开始删除,只删除第一个ov及ov以前的字符串 [root@localhost ~]# var1=${variable_1#*ov} [root@localhost ~]# echo $var1 e you,do you love me # 从头开始删除,最长删除ov及ov以前的字符串 [root@localhost ~]# var2=${variable_1##*ov} [root@localhost ~]# echo $var2 e me # 从尾部删除最短匹配的ov及ov后面的字符串 [root@localhost ~]# var3=${variable_1%ov*} [root@localhost ~]# echo $var3 i love you,do you l # 从尾部删除最长匹配的ov及ov后面的字符串 [root@localhost ~]# var4=${variable_1%%ov*} [root@localhost ~]# echo $var4 i l # 替换第一个小写的bin为大写的BIN [root@localhost ~]# echo $PATH /usr/local/go/bin:/data/golang_project/bin:/usr/java/jdk1.8.0_181-amd64/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin [root@localhost ~]# var5=${PATH/bin/BIN} [root@localhost ~]# echo $var5 /usr/local/go/BIN:/data/golang_project/bin:/usr/java/jdk1.8.0_181-amd64/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin # 替换所有小写的bin为大写的BIN [root@localhost ~]# var6=${PATH//bin/BIN} [root@localhost ~]# echo $var6 /usr/local/go/BIN:/data/golang_project/BIN:/usr/java/jdk1.8.0_181-amd64/BIN:/usr/local/sBIN:/usr/local/BIN:/usr/sBIN:/usr/BIN:/root/BIN