而bash中的循环得到重复的结果

时间:2017-03-09 06:50:59

标签: bash unix

$ cat grades.dat
santosh 65 65 65 65
john 85 92 78 94 88
andrea 89 90 75 90 86
jasper 84 88 80 92 84
santosh 99 99 99 99 99

脚本: -

#!/usr/bin/bash
filename="$1"
while read line
do
a=`grep -w "santosh" $1 | awk '{print$1}' |wc -l`
 echo "total is count of the file is  $a";

done <"$filename"

O / P

total is count of the file is  2
total is count of the file is  2
total is count of the file is  2
total is count of the file is  2
total is count of the file is  2

真正的O / P应该是 总数是这个文件的数量是2这样吧..请告诉我,我在上面的脚本中缺少。

1 个答案:

答案 0 :(得分:0)

虽然其他人已经向您展示了解决问题的更好方法,但您的问题的答案如下:

a=`grep -w "santosh" $1 | awk '{print$1}' |wc -l`

您通过while循环将名称存储在变量“line”中,但从不使用它。相反,你的循环总是寻找出现两次的“santosh”,因为你对被搜索文件中的所有5行运行相同的查询,所以你得到完全相同输出的5行。

您可以像这样更改当前脚本:

a=$(grep -w "$line" "$filename" | awk '{print$1}' | wc -l)

以上并不是其他人所指出的解决方案,但它确实解决了您的问题。