bash里关于string相关的处理
- 取字符串的长度:
${#VAR}
# a="HelloWorld"
# echo ${#a}
10- 字符串截断:
${VAR:POSITION}或${VAR:POSITION:LENGTH}
|
|
- 字符串匹配取最短:
${VAR#SUBSTRING}和${VAR%SUBSTRING}
|
|
注:#是从前向后,并且*号是紧随着的,而%则是从后向前匹配。*号是放在最后的。
- 字符串匹配取最长:
${VAR#SUBSTRING}和${VAR%SUBSTRING}
|
|
- 字符串替换:
${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
在线阅读本文 Guixing's Jail https://blog.khsing.net/2010/07/bashstring.html