如何从Bash变量中修剪空格?我有一个shell脚本,其中包含以下代码:var=`hg st -R "$path"`if [ -n "$var" ]; then
echo $varfi但是条件代码总是执行,因为hg st始终打印至少一个换行符。有没有一种简单的方法从$var(比如trim()在……里面PHP)?或是否有一个标准的方法来处理这个问题?我可以用SED或AWK,但我想对这个问题有一个更优雅的解决方案。
3 回答
守着一只汪
TA贡献1872条经验 获得超3个赞
FOO=' test test test 'echo -e "FOO='${FOO}'"# > FOO=' test test test 'echo -e "length(FOO)==${#FOO}"# > length(FOO)==16
[:space:]
tr
):
FOO=' test test test 'FOO_NO_WHITESPACE="$(echo -e "${FOO}" | tr -d '[:space:]')"echo -e "FOO_NO_WHITESPACE='${FOO_NO_WHITESPACE}'" # > FOO_NO_WHITESPACE='testtesttest'echo -e "length(FOO_NO_WHITESPACE)==${#FOO_NO_WHITESPACE}"# > length(FOO_NO_WHITESPACE)==12
FOO=' test test test 'FOO_NO_LEAD_SPACE="$(echo -e "${FOO}" | sed -e 's/^[[:space:]]*//')"echo -e "FOO_NO_LEAD_SPACE='${FOO_NO_LEAD_SPACE}'" # > FOO_NO_LEAD_SPACE='test test test 'echo -e "length(FOO_NO_LEAD_SPACE)==${#FOO_NO_LEAD_SPACE}"# > length(FOO_NO_LEAD_SPACE)==15
FOO=' test test test 'FOO_NO_TRAIL_SPACE="$(echo -e "${FOO}" | sed -e 's/[[:space:]]*$//')"echo -e "FOO_NO_TRAIL_SPACE='${FOO_NO_TRAIL_SPACE}'" # > FOO_NO_TRAIL_SPACE=' test test test'echo -e "length(FOO_NO_TRAIL_SPACE)==${#FOO_NO_TRAIL_SPACE}"# > length(FOO_NO_TRAIL_SPACE)==15
sed
FOO=' test test test 'FOO_NO_EXTERNAL_SPACE="$(echo -e "${FOO}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')" echo -e "FOO_NO_EXTERNAL_SPACE='${FOO_NO_EXTERNAL_SPACE}'"# > FOO_NO_EXTERNAL_SPACE='test test test'echo -e " length(FOO_NO_EXTERNAL_SPACE)==${#FOO_NO_EXTERNAL_SPACE}"# > length(FOO_NO_EXTERNAL_SPACE)==14
echo -e "${FOO}" | sed ...
sed ... <<<${FOO}
FOO_NO_TRAIL_SPACE="$(sed -e 's/[[:space:]]*$//' <<<${FOO})"
添加回答
举报
0/150
提交
取消