Shell字符串截取(# %)

从指定字符(子字符串)开始截取

这种截取方式无法指定字符串长度,只能从指定字符(子字符串)截取到字符串末尾。Shell 可以截取指定字符(子字符串)右边的所有字符,也可以截取左边的所有字符。

1) 使用 # 号截取右边字符

使用#号可以截取指定字符(或者子字符串)右边的所有字符,具体格式如下:

${string#*chars}

其中,string 表示要截取的字符,chars 是指定的字符(或者子字符串),*是通配符的一种,表示任意长度的字符串。*chars连起来使用的意思是:忽略左边的所有字符,直到遇见 chars(chars 不会被截取)。

请看下面的例子:

 
  1. url="http://c.biancheng.net/index.html"
  2. echo ${url#*:}

结果为//c.biancheng.net/index.html

以下写法也可以得到同样的结果:

 
  1. echo ${url#*p:}
  2. echo ${url#*ttp:}


如果不需要忽略 chars 左边的字符,那么也可以不写*,例如:

 
  1. url="http://c.biancheng.net/index.html"
  2. echo ${url#http://}

结果为c.biancheng.net/index.html

注意,以上写法遇到第一个匹配的字符(子字符串)就结束了。例如:

 
  1. url="http://c.biancheng.net/index.html"
  2. echo ${url#*/}

结果为/c.biancheng.net/index.html。url 字符串中有三个/,输出结果表明,Shell 遇到第一个/就匹配结束了。

如果希望直到最后一个指定字符(子字符串)再匹配结束,那么可以使用##,具体格式为:

${string##*chars}

请看下面的例子:

扫描二维码关注公众号,回复: 16773821 查看本文章
 
  1. #!/bin/bash
  2.  
  3. url="http://c.biancheng.net/index.html"
  4. echo ${url#*/} #结果为 /c.biancheng.net/index.html
  5. echo ${url##*/} #结果为 index.html
  6.  
  7. str="---aa+++aa@@@"
  8. echo ${str#*aa} #结果为 +++aa@@@
  9. echo ${str##*aa} #结果为 @@@

2) 使用 % 截取左边字符

使用%号可以截取指定字符(或者子字符串)左边的所有字符,具体格式如下:

${string%chars*}

请注意*的位置,因为要截取 chars 左边的字符,而忽略 chars 右边的字符,所以*应该位于 chars 的右侧。其他方面%#的用法相同,这里不再赘述,仅举例说明:

 
 
  1. #!/bin/bash
  2.  
  3. url="http://c.biancheng.net/index.html"
  4. echo ${url%/*} #结果为 http://c.biancheng.net
  5. echo ${url%%/*} #结果为 http:
  6.  
  7. str="---aa+++aa@@@"
  8. echo ${str%aa*} #结果为 ---aa+++
  9. echo ${str%%aa*} #结果为 ---

转自:http://c.biancheng.net/view/1120.html

猜你喜欢

转载自blog.csdn.net/liuwkk/article/details/108831656