Tekkaman

导航

 

[bash's parameter expansion]

 #: find first from left, remove-left

 ##: find last from left, remove left

 %: find first from right, remove right

 %%: find last from right, remove right

 example 1:

1 parameter     result
2 -----------   ------------------------------
3 ${NAME}       polish.ostrich.racing.champion
4 ${NAME#*.}           ostrich.racing.champion
5 ${NAME##*.}                         champion
6 ${NAME%%.*}   polish
7 ${NAME%.*}    polish.ostrich.racing

 example 2:

1 parameter     result
2 -----------   --------------------------------------------------------
3 ${FILE}       /usr/share/java-1.4.2-sun/demo/applets/Clock/Clock.class
4 ${FILE#*/}     usr/share/java-1.4.2-sun/demo/applets/Clock/Clock.class
5 ${FILE##*/}                                                Clock.class
6 ${FILE%%/*}
7 ${FILE%/*}    /usr/share/java-1.4.2-sun/demo/applets/Clock

 string slice: 

${string:2:1}   # The third character of string (0, 1, 2 = third)
${string:1}     # The string starting from the second character
                # Note: this is equivalent to ${string#?}
${string%?}     # The string with its last character removed.
${string: -1}   # The last character of string
${string:(-1)}  # The last character of string, alternate syntax
                # Note: string:-1 means something entirely different; see below.

${file%.mp3}    # The filename without the .mp3 extension
                # Very useful in loops of the form: for file in *.mp3; do ...
${file%.*}      # The filename without its last extension
${file%%.*}     # The filename without all of its extensions
${file##*.}     # The extension only, assuming there is one. If not, will expand to ${file}

 toupper (^) and tolower (,):

1 # string='hello, World!'
2 parameter     result
3 -----------   --------------------------------------------------------
4 ${string^}    Hello, World! # First character to uppercase
5 ${string^^}   HELLO, WORLD! # All characters to uppercase
6 ${string,}    hello, World! # First character to lowercase
7 ${string,,}   hello, world! # All characters to lowercase

assignment:

1 ${var-word}             # if var is defined, use var; otherwise, "word"
2 ${var+word}             # if var is defined, use "word"; otherwise, nothing
3 ${var=word}             # if var is defined, use var; otherwise, use "word" AND...
4                         #   also assign "word" to var
5 ${var?error}            # if var is defined, use var; otherwise print "error" and exit

参考: http://bash.cumulonim.biz/BashFAQ(2f)073.html

 

posted on 2013-12-06 14:05  Tekkaman  阅读(300)  评论(0)    收藏  举报