如何删除shell字符串变量中的前缀的和后缀的空格?
var=" hello world! " echo "var=\"$var\""
var=" hello world! "
1. echo
newvar=$(echo $var) echo "newvar=\"$newvar\""
newvar="hello world!"
2. Parameter Substitution
newvar=${var#"${var%%[![:blank:]]*}"} newvar=${newvar%"${newvar##*[![:blank:]]}"} echo "newvar=\"$newvar\""
newvar="hello world!"
3. Pattern Matching
shopt -s extglob newvar=${var##+( )} newvar=${newvar%%+( )} shopt -u extglob echo "newvar=\"$newvar\""
newvar="hello world!"
4. sed
newvar=$(echo "$var"|sed 's/\(^[[:blank:]]\+\|[[:blank:]]\+$\)//g') echo "newvar=\"$newvar\""
newvar="hello world!"
5. awk
newvar=$(echo "$var"|awk 'gsub(/^[[:blank:]]+|[[:blank:]]+$/,"")') echo "newvar=\"$newvar\""
newvar="hello world!"
-fin-