在shell脚本中求和

时间:2011-01-06 05:13:51

标签: linux shell sum

为什么我不能在此脚本中创建总单词总和?我得到的结果如下:

 120+130

但它不是250(正如我预期的那样)!有什么理由吗?

#!/bin/bash

while [ -z "$count" ] ;
do
    echo -e "request :: please enter file name "
    echo -e "\n\tfile one : \c"
    read count

    itself=counter.sh

    countWords=`wc -w $count |cut -d ' ' -f 1`
    countLines=`wc -l $count |cut -d ' ' -f 1`
    countWords_=`wc -w $itself |cut -d ' ' -f 1`

    echo "Number of lines: " $countLines
    echo "Number of words: " $countWords
    echo "Number of words -script: " $countWords_

    echo "Number of words -total " $countWords+$countWords_  

done

if [ ! -e $count ] ; then
    echo -e "error :: file one $count doesn't exist. can't proceed."
    read empty
    exit 1
fi

2 个答案:

答案 0 :(得分:6)

  

echo“单词数量 - 总数”   $ countWords + $ countWords _

你想要这个:

echo "Number of words -total $((countWords + countWords_))"

修改

以下是对脚本的一些优化。

  1. while循环似乎毫无意义 因为count将被设置为 确定里面做这个 1循环while循环。
  2. 您的if检查是否存在 文件应该在你之前发生 使用该文件。
  3. 您无需将脚本名称硬编码到变量itself,您可以使用$0
  4. 由于您使用的是bash,我冒昧地通过使用流程替换来消除对cut的需求。
  5. 以下是修订后的脚本:

    #!/bin/bash
    
    echo -e "request :: please enter file name "
    echo -e "\n\tfile one : \c"
    read count
    
    if [ ! -e "$count" ] ; then
        echo "error :: file one $count doesn't exist. can't proceed."
        exit 1
    fi
    
    itself="$0"
    
    read countWords _ < <(wc -w $count)
    read countLines _ < <(wc -l $count)
    read countWords_ _ < <(wc -w $itself)
    
    echo "Number of lines: '$countLines'"
    echo "Number of words: '$countWords'"
    echo "Number of words -script: '$countWords_'"
    
    echo "Number of words -total $((countWords + countWords_))"
    

答案 1 :(得分:1)

解决这个问题的一种方法是:

echo `expr $countWords + $countWords_`