如何从 Bash 变量中修剪空格? [英] How to trim whitespace from a Bash variable?

查看:32
本文介绍了如何从 Bash 变量中修剪空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有此代码的 shell 脚本:

I have a shell script with this code:

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

但条件代码总是会执行,因为hg 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 (like trim() in PHP)?

  • 是否有处理这个问题的标准方法?

我可以使用 sedAWK,但我想有一个更优雅的解决方案来解决这个问题.

I could use sed or AWK, but I'd like to think there is a more elegant solution to this problem.

推荐答案

一个简单的答案是:

echo "   lol  " | xargs

Xargs 将为您进行修剪.这是一个命令/程序,没有参数,返回修剪后的字符串,就这么简单!

Xargs will do the trimming for you. It's one command/program, no parameters, returns the trimmed string, easy as that!

注意:这不会删除所有内部空格,所以 "foo bar" 保持不变;它不会变成 "foobar".但是,多个空格会被压缩为单个空格,所以 "foo bar" 会变成 "foo bar".此外,它不会删除行尾字符.

Note: this doesn't remove all internal spaces so "foo bar" stays the same; it does NOT become "foobar". However, multiple spaces will be condensed to single spaces, so "foo bar" will become "foo bar". In addition it doesn't remove end of lines characters.

这篇关于如何从 Bash 变量中修剪空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆