2015年6月9日 星期二

操作字串

ref: http://www.linuxtopia.org/online_books/advanced_bash_scripting_guide/string-manipulation.html

就直接 copy ...

Substring Removal

${string#substring}
Strips shortest match of $substring from front of $string.

${string##substring}
Strips longest match of $substring from front of $string.

stringZ=abcABC123ABCabc
#       |----|
#       |----------|

echo ${stringZ#a*C}      # 123ABCabc
# Strip out shortest match between 'a' and 'C'.

echo ${stringZ##a*C}     # abc
# Strip out longest match between 'a' and 'C'.

反過來:

${string%%substring}
Strips longest match of $substring from back of $string.
stringZ=abcABC123ABCabc
#                    ||
#        |------------|

echo ${stringZ%b*c}      # abcABC123ABCa
# Strip out shortest match between 'b' and 'c', from back of $stringZ.

echo ${stringZ%%b*c}     # a
# Strip out longest match between 'b' and 'c', from back of $stringZ.