如何从猛砸变量修剪空白? [英] How to trim whitespace from a Bash variable?
问题描述
我有这个code shell脚本:
I have a shell script with this code:
var=`hg st -R "$path"`
if [ -n "$var" ]; then
echo $var
fi
但条件code总是执行,因为汞ST
始终打印至少有一个换行符。
But the conditional code always executes, because hg st
always prints at least one newline character.
- 是否有从
$ VAR
剥离空白(如修剪()的简单方式
中的PHP )?
- Is there a simple way to strip whitespace from
$var
(liketrim()
in PHP)?
或
- 是否有处理这个问题的标准方式?
我可以使用 SED 或的 AWK ,但我想,认为还有一个更优雅的解决了这个问题。
I could use sed or AWK, but I'd like to think there is a more elegant solution to this problem.
推荐答案
让我们来定义包含变量前置,和中间的空格:
Let's define a variable containing leading, trailing, and intermediate whitespace:
FOO=' test test test '
echo -e "FOO='${FOO}'"
# > FOO=' test test test '
echo -e "length(FOO)==$(echo -ne "${FOO}" | wc -m)"
# > length(FOO)==16
echo命令使用的选项 -n
来避免增加返回字符,并造成 WC -m
算一笔附加的字符。
The echo command used the option -n
to avoid adding a return character and causing wc -m
count an additional character.
如何删除所有空格(由表示[[:空间:]]
)
How to remove all whitespace (denoted by [[:space:]]
):
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)==$(echo -ne "${FOO_NO_WHITESPACE}" | wc -m)"
# > length(FOO_NO_WHITESPACE)==12
如何删除前导空格只:
How to remove leading whitespace only:
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)==$(echo -ne "${FOO_NO_LEAD_SPACE}" | wc -m)"
# > length(FOO_NO_LEAD_SPACE)==15
如何删除尾随空格只:
How to remove trailing whitespace only:
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)==$(echo -ne "${FOO_NO_TRAIL_SPACE}" | wc -m)"
# > 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)==$(echo -ne "${FOO_NO_EXTERNAL_SPACE}" | wc -m)"
# > length(FOO_NO_EXTERNAL_SPACE)==14
另外,如果您的bash支持的话,你可以替换回声-e$ {} FOO| SED ...
与 SED ...<<< $ {FOO}
,像这样(尾部空白):
Alternatively, if your bash supports it, you can replace echo -e "${FOO}" | sed ...
with sed ... <<<${FOO}
, like so (for trailing whitespace):
FOO_NO_TRAIL_SPACE="$(sed -e 's/[[:space:]]*$//' <<<${FOO})"
这篇关于如何从猛砸变量修剪空白?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!