AI智能
改变未来

Shell笔记1-变量替换


变量替换

  1. ${变量#匹配规则} # 从头开始匹配, 最短删除
  2. ${变量##匹配规则} # 从头开始匹配, 最长删除

例:

variable_1=\"I love you , Do you love me\"
~$ var1=${variable_1#*ov}~$  echo $var1~$ e you, Do you love me
~$ var2=${variable_1##*ov}~$ echo $var2~$ e me
  1. ${变量%匹配规则} # 从尾开始匹配, 最短删除
  2. ${变量%匹配规则} # 从尾开始匹配, 最长删除

例:

~$ var3=${variable_1%ov*}~$ echo  $var3~$ I love you, Do you l
~$ var4=${variable_1%%ov*}~$ echo  $var4~$ I l
  1. ${变量/旧字符串/新字符串} # 替换变量内的旧字符串为新字符串,只替换第一个
  2. ${变量//旧字符串/新字符串} # 替换变量内的旧字符串为新字符串,全部替换

例:

echo  $PATH/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
~$ var5=${PATH/bin/BIN}~$ echo $var5/usr/local/sBIN:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
~$ var6=${PATH//bin/BIN}~$ echo $var6/usr/local/sBIN:/usr/local/BIN:/usr/sBIN:/usr/BIN:/sBIN:/BIN:/usr/games:/usr/local/games:/snap/BIN
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » Shell笔记1-变量替换