我有一个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'

其他回答

var = '  a b  '
# remove all white spaces
new=$(echo $var |  tr -d ' ')
# remove leading and trailing whitespaces
new=$(echo $var)

ab
a b

如果启用了shop -s extglob,那么下面是一个简洁的解决方案。

这招对我很管用:

text="   trim my edges    "

trimmed=$text
trimmed=${trimmed##+( )} #Remove longest matching series of spaces from the front
trimmed=${trimmed%%+( )} #Remove longest matching series of spaces from the back

echo "<$trimmed>" #Adding angle braces just to make it easier to confirm that all spaces are removed

#Result
<trim my edges>

用更少的行数来获得相同的结果:

text="    trim my edges    "
trimmed=${${text##+( )}%%+( )}

使用Bash的扩展模式匹配功能(shopt -s extglob),你可以这样使用:

修剪{# # * ()}

删除任意数量的前导空格。

当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

要从左到第一个单词删除空格和制表符,输入:

echo "     This is a test" | sed "s/^[ \t]*//"

cyberciti.biz /技巧/ delete-leading-spaces-from-front-of-each-word.html