我有一个shell脚本与这段代码:
var=`hg st -R "$path"`
if [ -n "$var" ]; then
echo $var
fi
但是条件代码总是执行,因为hg st总是打印至少一个换行符。
是否有一个简单的方法从$var中剥离空白(如PHP中的trim())?
or
有没有处理这个问题的标准方法?
我可以使用sed或AWK,但我认为有一个更优雅的解决方案来解决这个问题。
我有一个shell脚本与这段代码:
var=`hg st -R "$path"`
if [ -n "$var" ]; then
echo $var
fi
但是条件代码总是执行,因为hg st总是打印至少一个换行符。
是否有一个简单的方法从$var中剥离空白(如PHP中的trim())?
or
有没有处理这个问题的标准方法?
我可以使用sed或AWK,但我认为有一个更优雅的解决方案来解决这个问题。
当前回答
我所知道的单行用例最简单的方法是:
echo " ABC " | sed -e 's# \+\(.\+\) \+#\1#'
工作原理:
-e启用高级正则表达式 我使用# sed,因为我不喜欢“凌乱的库”模式,如/\////\/\\\/\/ Sed希望转义大多数正则表达式控制字符,因此所有\ 否则就是^ +(.+)+$,也就是开头的空格,一组no。1,空格在最后。 所有这些都被“第一组”所取代。
因此,ABC变成了ABC。
这应该在使用sed的最新系统上得到支持。
对于标签来说,就是这样
echo " ABC " | sed -e 's#[\t ]\+\(.\+\)[\t ]\+#\1#'
对于多行内容,已经需要其他答案中描述的[:space:]这样的字符类,并且可能不是所有sed实现都支持。
参考资料:Sed手册
其他回答
Bash有一个称为参数展开的特性,它允许基于所谓的模式替换字符串(模式类似于正则表达式,但有基本的区别和限制)。 [flussence的原文:Bash有正则表达式,但它们隐藏得很好:]
下面演示如何从变量值中删除所有空白(甚至来自内部)。
$ var='abc def'
$ echo "$var"
abc def
# Note: flussence's original expression was "${var/ /}", which only replaced the *first* space char., wherever it appeared.
$ echo -n "${var//[[:space:]]/}"
abcdef
当IFS变量被设置为其他变量时,我需要从脚本中删除空白。依赖Perl实现了这个目的:
# trim() { echo $1; } # This doesn't seem to work, as it's affected by IFS
trim() { echo "$1" | perl -p -e 's/^\s+|\s+$//g'; }
strings="after --> , <-- before, <-- both --> "
OLD_IFS=$IFS
IFS=","
for str in ${strings}; do
str=$(trim "${str}")
echo "str= '${str}'"
done
IFS=$OLD_IFS
Read已经修整了空白,所以在bash中你可以这样做:
$ read foo <<< " foo bar two spaces follow "
$ echo ".$foo."
.foo bar two spaces follow.
POSIX兼容的版本稍长一些
$ read foo << END
foo bar two spaces follow
END
$ echo ".$foo."
.foo bar two spaces follow.
# Trim whitespace from both ends of specified parameter
trim () {
read -rd '' $1 <<<"${!1}"
}
# Unit test for trim()
test_trim () {
local foo="$1"
trim foo
test "$foo" = "$2"
}
test_trim hey hey &&
test_trim ' hey' hey &&
test_trim 'ho ' ho &&
test_trim 'hey ho' 'hey ho' &&
test_trim ' hey ho ' 'hey ho' &&
test_trim $'\n\n\t hey\n\t ho \t\n' $'hey\n\t ho' &&
test_trim $'\n' '' &&
test_trim '\n' '\n' &&
echo passed
使用AWK:
echo $var | awk '{gsub(/^ +| +$/,"")}1'