我有一个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,但我认为有一个更优雅的解决方案来解决这个问题。
当前回答
使用Bash的扩展模式匹配功能(shopt -s extglob),你可以这样使用:
修剪{# # * ()}
删除任意数量的前导空格。
其他回答
var = ' a b '
# remove all white spaces
new=$(echo $var | tr -d ' ')
# remove leading and trailing whitespaces
new=$(echo $var)
ab
a b
这修整了前端和末端的多个空间
whatever=${whatever%% *}
无论= ${无论# *}
这就是我所做的,结果完美而简单:
the_string=" test"
the_string=`echo $the_string`
echo "$the_string"
输出:
test
#!/bin/bash
function trim
{
typeset trimVar
eval trimVar="\${$1}"
read trimVar << EOTtrim
$trimVar
EOTtrim
eval $1=\$trimVar
}
# Note that the parameter to the function is the NAME of the variable to trim,
# not the variable contents. However, the contents are trimmed.
# Example of use:
while read aLine
do
trim aline
echo "[${aline}]"
done < info.txt
# File info.txt contents:
# ------------------------------
# ok hello there $
# another line here $
#and yet another $
# only at the front$
#$
# Output:
#[ok hello there]
#[another line here]
#[and yet another]
#[only at the front]
#[]
这没有不必要的通配符问题,而且,内部空白是未修改的(假设$IFS被设置为默认值,即' \t\n')。
它一直读取到第一个换行符(但不包括换行符)或字符串的结尾,以先到者为准,并删除任何前导和尾随空格以及\t字符的混合。如果你想保留多行(同时去掉开头和结尾换行符),请使用read -r -d " var << eof;但是请注意,如果您的输入恰好包含\neof,它将在之前被切断。(其他形式的空白,即\r、\f和\v,即使您将它们添加到$IFS,也不会被剥离。)
read -r var << eof
$var
eof