变量模式匹配运算符

Shell中还提供了一组模式匹配运算符,见下表:

运算符

${variable#pattern}

如果模式匹配变量值的开头,则删除匹配的最短部分,并返回剩下的部分,变量原值不变。

${variable##pattern}

如果模式匹配变量值的开头,则删除匹配的最长部分,并返回剩下的部分,变量原值不变。

${variable%pattern}

如果模式匹配变量值的结尾,则删除匹配的最短部分,并返回剩下的部分,变量原值不变。

${variable%%pattern}

如果模式匹配变量值的结尾,则删除匹配的最长部分,并返回剩下的部分,变量原值不变。

${#variable}

返回变量中字母的数量。


    

 #${variable#pattern}示例:
    /> pathname="/home/stephen/mycode/test.h"
    /> echo ${pathname#/home}        #变量pathname开始处匹配/home的最短部分被删除。
    /stephen/mycode/test.h
    /> echo $pathname                       #pathname的原值不变。
    /home/stephen/mycode/test.h

    #${variable##pattern}示例:
    /> pathname="/home/stephen/mycode/test.h"
    /> echo ${pathname##*/}            #变量pathname开始处匹配*/的最长部分被删除,*表示任意字符。
    test.h
    /> echo $pathname                       #pathname的原值不变。
    /home/stephen/mycode/test.h

    #${variable%pattern}示例:
    /> pathname="/home/stephen/mycode/test.h"
    /> echo ${pathname%/*}             #变量pathname结尾处匹配/*的最短部分被删除。
    /home/stephen/mycode
    /> echo $pathname                       #pathname的原值不变。
    /home/stephen/mycode/test.h

    #${variable%%pattern}示例:
    /> pathname="/home/stephen/mycode/test.h"
    /> echo ${pathname%%/*}          #变量pathname结尾处匹配/*的最长部分被删除,这里所有字符串均被删除。

    /> echo $pathname                       #pathname的原值不变。
    /home/stephen/mycode/test.h

    #${#variable}示例:
    /> name="stephen liu"
    /> echo ${#name}
    11

  

posted @ 2019-03-13 13:57  山的那一边  阅读(310)  评论(0)    收藏  举报