在unix like系统的shell中,提供了很多操作字符串变量的灵活语法,我们接下来依次来看一看。
apple@kissAir: ~$path=$PATH
apple@kissAir: ~$echo $path
/opt/local/bin:/opt/local/sbin:/Users/apple/.rvm/gems/ruby-2.1.1/bin:/Users/apple/.rvm/gems/ruby-2.1.1@global/bin:/Users/apple/.rvm/rubies/ruby-2.1.1/bin:/Users/apple/.rvm/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/
local/bin:/opt/X11/bin
1 从左向右删除最短匹配字符串: ${var#key_str}
apple@kissAir: ~$echo ${path#/*sbin}
:/Users/apple/.rvm/gems/ruby-2.1.1/bin:/Users/apple/.rvm/gems/ruby-2.1.1@global/bin:/Users/apple/.rvm/rubies/ruby-2.1.1/bin:/Users/apple/.rvm/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/
local/bin:/opt/X11/bin
2 从左向右删除最长匹配字符串:${var##key_str}
apple@kissAir: ~$echo ${path##/*sbin}
:/usr/local/bin:/opt/X11/bin
3 从右向左删除最短匹配字符串:${var%key_str}
apple@kissAir: ~$echo ${path%/*bin}
/opt/local/bin:/opt/local/sbin:/Users/apple/.rvm/gems/ruby-2.1.1/bin:/Users/apple/.rvm/gems/ruby-2.1.1@global/bin:/Users/apple/.rvm/rubies/ruby-2.1.1/bin:/Users/apple/.rvm/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/
local/bin:/opt/X11
4 从右向左删除最长匹配字符串:${var%%key_str}
apple@kissAir: ~$echo ${path%%/*bin}
5 用key_str1替换第一个key_str0字符串:${var/key_str0/key_str1}
apple@kissAir: ~$echo ${path/sbin/SBIN}
/opt/local/bin:/opt/local/SBIN:/Users/apple/.rvm/gems/ruby-2.1.1/bin:/Users/apple/.rvm/gems/ruby-2.1.1@global/bin:/Users/apple/.rvm/rubies/ruby-2.1.1/bin:/Users/apple/.rvm/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/
local/bin:/opt/X11/bin
6 用key_str1替换所有的key_str0字符串:${var//key_str0/key_str1}
apple@kissAir: ~$echo ${path//sbin/SBIN}
/opt/local/bin:/opt/local/SBIN:/Users/apple/.rvm/gems/ruby-2.1.1/bin:/Users/apple/.rvm/gems/ruby-2.1.1@global/bin:/Users/apple/.rvm/rubies/ruby-2.1.1/bin:/Users/apple/.rvm/bin:/usr/bin:/bin:/usr/SBIN:/SBIN:/usr/
local/bin:/opt/X11/bin
7 若变量未赋过值则使用默认值,否则使用赋予的值: ${var-default_var}
apple@kissAir: ~$echo $var
apple@kissAir: ~$echo ${var-zero}
zero
apple@kissAir: ~$var=one
apple@kissAir: ~$echo $var
one
8 若变量为赋过值或其值为空字符串则使用默认值,否则使用赋予的值:${var:-default_var}
apple@kissAir: ~$var=
apple@kissAir: ~$echo ${var-null}
apple@kissAir: ~$echo ${var:-null}
null
apple@kissAir: ~$var=one
apple@kissAir: ~$echo $var
one
9 7和8的其他变形语法(摘自《鸟哥自学linux》):
10 待续 :)