要从Bash变量中修剪空格,您可以使用以下方法:
${variable%}
和${variable#}
:variable=" Hello World! "
trimmed_variable="${variable#"${variable%%[![:space:]]*}"}"
trimmed_variable="${trimmed_variable%"${trimmed_variable##*[![:space:]]}"}"
echo "$trimmed_variable"
sed
命令:variable=" Hello World! "
trimmed_variable=$(echo "$variable" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
echo "$trimmed_variable"
awk
命令:variable=" Hello World! "
trimmed_variable=$(echo "$variable" | awk '{$1=$1;print}')
echo "$trimmed_variable"
tr
命令:variable=" Hello World! "
trimmed_variable=$(echo "$variable" | tr -d '[:space:]')
echo "$trimmed_variable"
xargs
命令:variable=" Hello World! "
trimmed_variable=$(echo "$variable" | xargs)
echo "$trimmed_variable"
这些方法都可以从Bash变量中修剪空格。您可以根据自己的需求选择合适的方法。
领取专属 10元无门槛券
手把手带您无忧上云