# how can I do calculation of numbers from text file in shell script

I have a text file named `t1.txt`, it contains:

``````300
400
500
600
``````

Now I want to find how many numbers in this text are less than 450 And I give the following code:

``````b=0
for i in \$(cat t1.txt)
do
if [\$i -lt 450]
then
((b=b+1))
fi
done
echo b
``````

but it doesn't work.

What should I do? Thank you.

• `echo b` is very different than `echo \$b` – thrig Oct 12 '16 at 23:05

``````b=0
for i in \$(cat t1.txt)
do
# convert float to int
i=\$(echo \$i | cut -d. -f1)
if [ \$i -lt 450 ] # comment: need spaces next to the the square brackets
then
((b=b+1))
fi
done
echo \$b  # comment: need to \$
``````
• what if the numbers in text file are not integer? They are float for example. It will show the error of `integer expression expected` – Leonard Oct 13 '16 at 2:39
• Bash cannot do floats on it's own, unless you something like `bc`. So if you have floats, there is no way to do an `if` on it. A hack is to drop the float part and make the number an integer. – GMaster Oct 13 '16 at 2:54
• I've just edited the answer to handle floats. – GMaster Oct 13 '16 at 3:10

Awk is good at this:

``````\$ awk '\$1<450{c++} END{print c+0}' t1.txt
2
``````

How it works:

• `\$1<450 {c++}`

For any line for which the first field is less than 450, the variable `c` is incremented by one.

• `END{print c+0}`

After we have read in all the lines, the value of `c` is printed.

The numbers can be integer or floating point. Awk understands both.

``````#!/bin/bash