0

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.

  • 1
    echo b is very different than echo $b – thrig Oct 12 '16 at 23:05
1
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
1

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.

0
#!/bin/bash

    while read line
    do
            if [ "${line}" -lt "450" ]
            then
                    count=$((count+1))
            fi
    done < t.txt

    echo ${count}
  • This is indeed a good solution, but the answer could benefit from some explanation about how it works (and in particular where it differs from the one that didn't work for the OP) – Eric Renouf Oct 13 '16 at 1:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.