如何在shell脚本中只添加正数?

时间:2014-04-17 05:55:04

标签: shell sum

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"

2 个答案:

答案 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脚本编写指南。