痴心VS绝对 发表于 2018-8-20 12:24:02

Shell中的${}、##和%%几点说明

  假设我们定义了一个变量为:
  复制代码 代码如下:
  file=/dir1/dir2/dir3/my.file.txt
  可以用${ }分别替换得到不同的值:
  复制代码 代码如下:
  ${file#*/}:删掉第一个 / 及其左边的字符串:dir1/dir2/dir3/my.file.txt
  ${file##*/}:删掉最后一个 /及其左边的字符串:my.file.txt
  ${file#*.}:删掉第一个 .及其左边的字符串:file.txt
  ${file##*.}:删掉最后一个 .及其左边的字符串:txt
  ${file%/*}:删掉最后一个/及其右边的字符串:/dir1/dir2/dir3
  ${file%%/*}:删掉第一个 /及其右边的字符串:(空值)
  ${file%.*}:删掉最后一个.及其右边的字符串:/dir1/dir2/dir3/my.file
  ${file%%.*}:删掉第一个.   及其右边的字符串:/dir1/dir2/dir3/my
  记忆的方法为:
  复制代码 代码如下:
  # 是 去掉左边(键盘上#在 $ 的左边)
  %是去掉右边(键盘上% 在$ 的右边)
  单一符号是最小匹配;两个符号是最大匹配
  ${file:0:5}:提取最左边的 5 个字节:/dir1
  ${file:5:5}:提取第 5 个字节右边的连续5个字节:/dir2
  也可以对变量值里的字符串作替换:
  复制代码 代码如下:
  ${file/dir/path}:将第一个dir 替换为path:/path1/dir2/dir3/my.file.txt
  ${file//dir/path}:将全部dir 替换为 path:/path1/path2/path3/my.file.txt
  (2)
  ## #后面如果直接跟匹配的字符串,会删除前面的或者左边的所有字符串,主要通配符的位置(# ## *必须在前面比如*llo);跟完整字符串只匹配第一个,效果一样,如果完整字符串不是第一个,原样输出
  %% %后面如果直接跟匹配的字符串,会删除前面的或者右边边的所有字符串,主要通配符的位置(% %% *必须在在后面比如he*),跟完整字符串原样输出
  比如
  a=" this is helloa maomaochong hello this!"
  35 #echo ${a#hello} //this is helloa maomaochong hello this!
  36 #echo ${a##hello}//this is helloa maomaochong hello this!
  37 #echo ${a#*llo} //a maomaochong hello this!
  38 #echo ${a##*llo} //this !
  39 echo ${a%this}//this is helloa maomaochong hello this!
  40 echo ${a%%this}//this is helloa maomaochong hello this!
  41 #echo ${a%he*} //   this is helloa maomaochong
  42 #echo ${a%%he*}//this is
  //

页: [1]
查看完整版本: Shell中的${}、##和%%几点说明