我有一个shell脚本与这段代码:

var=`hg st -R "$path"`
if [ -n "$var" ]; then
    echo $var
fi

但是条件代码总是执行,因为hg st总是打印至少一个换行符。

是否有一个简单的方法从$var中剥离空白(如PHP中的trim())?

or

有没有处理这个问题的标准方法?

我可以使用sed或AWK,但我认为有一个更优雅的解决方案来解决这个问题。


当前回答

为了删除字符串开头和结尾的所有空格(包括行末字符):

echo $variable | xargs echo -n

这也将删除重复的空格:

echo "  this string has a lot       of spaces " | xargs echo -n

Produces: 'this string has a lot of spaces'

其他回答

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

您可以使用老式的tr。例如,它返回git存储库中已修改文件的数量,删除空白。

MYVAR=`git ls-files -m|wc -l|tr -d ' '`
var='   a b c   '
trimmed=$(echo $var)

使用这个简单的Bash参数展开:

$ x=" a z     e r ty "
$ echo "START[${x// /}]END"
START[azerty]END
#Execute this script with the string argument passed in double quotes !! 
#var2 gives the string without spaces.
#$1 is the string passed in double quotes
#!/bin/bash
var2=`echo $1 | sed 's/ \+//g'`
echo $var2