bash里关于string相关的处理
- 取字符串的长度:
${#VAR}
# a="HelloWorld"
# echo ${#a}
10
- 字符串截断:
${VAR:POSITION}
或${VAR:POSITION:LENGTH}
# a="HelloWorld"
# echo ${a:5}
World
# echo ${a:4:3}
oWo
- 字符串匹配取最短:
${VAR#SUBSTRING}
和${VAR%SUBSTRING}
# a="HelloWorld"
# echo ${a#*o}
World
# echo ${a%o*}
HelloW
注:#
是从前向后,并且*号是紧随着的,而%
则是从后向前匹配。*号是放在最后的。
- 字符串匹配取最长:
${VAR#SUBSTRING}
和${VAR%SUBSTRING}
# a="HelloWorld"
# echo ${a#*o}
rld
# echo ${a%o*}
Hell
- 字符串替换:
${VAR//PATTERN/REPLACEMENT}
# a="HelloWorld"
# echo ${a//World/Earth}
HelloEarth
- 确定匹配位置:
expr STRING : REGEX
# a="HelloWorld"
# expr $a : ".*o"
注:这里的REGEX从名字上就说明了是一个正则表达式。
Update:详细请参考
- Advanced Bash-Scripting Guide: Table B-5. String Operations
- The Geek Stuff: Bash String Manipulation Examples – Length, Substring, Find and Replace
Last modified on 2010-07-23