sum=0
for file in $*
do
for number in `grep -wo "[0-9]*" $file`
do
if [ $number > 0 ]
then
sum=$(($sum+numar))
fi
done
done
echo "Suma este: $sum"
答案 0 :(得分:1)
shell执行两种比较测试:lexicographic(string)和numeric。词典编纂的是=
,>
,<
等。数字的是-eq
,-gt
,-lt
等。当你说你想要“正数”,你要求进行数字比较。
这两种类型之间存在很大差异。观察:
$ [ -2 > 0 ] && echo yes
yes
$ [ -2 -gt 0 ] && echo yes
词典比较>
认为-2
大于0
,因为-
和0
在字符集中的相对位置。数字-gt
在算术方面理解减号。
因此,行if [ $number > 0 ]
不能达到你想要的效果。
man bash
解释如下:
string1 = string2 True if the strings are equal. = should be used with the test command for POSIX conformance. string1 != string2 True if the strings are not equal. string1 < string2 True if string1 sorts before string2 lexicographically. string1 > string2 True if string1 sorts after string2 lexicographically arg1 OP arg2 OP is one of -eq, -ne, -lt, -le, -gt, or -ge. These arithmetic binary operators return true if arg1 is equal to, not equal to, less than, less than or equal to, greater than, or greater than or equal to arg2, respectively. Arg1 and arg2 may be positive or negative integers.
答案 1 :(得分:0)
if [[ $number -gt 0 ]];
另外,请参阅http://robertmuth.blogspot.nl/2012/08/better-bash-scripting-in-15-minutes.html?m=1了解更多bash脚本编写指南。