Michele Pardini
Michele Pardini

Reputation: 13

How to convert a number read from a file from str to int?

I use bash, I have to read a file that contains many lines

Each line is composed by a single number. Then, for each line (number) I have to check if value > 80.

And here's my problem, no matter what I try, I always get:

>integer expression expected

after the if condition. That's because the variable I use to put the value of the line is a string.

Here's my original file

[root@michelep_centos2 ~]# cat temp1

0

0

0

98

0

0

79

0

81

In the bash script I have

##!/bin/bash

file=/root/temp1


while IFS= read -r line

do

        if [ 'expr $line /1' -gt 80 ]

        then echo "hit>80"

        fi

done <"$file"

And here expr returns error as $line is a string. I have tried using another variable

val=$(($line + 0))

if [ $val -gt 80 ]

Here the if condition returns "integer expression expected"

I have used also echo

val=$(echo "$((line /1))") 

if [ $val -gt 80 ]

I get

syntax error: invalid arithmetic operator (error token is ...

from echo command and of course again the if condition returns

integer expression expected

Upvotes: 1

Views: 139

Answers (2)

P....
P....

Reputation: 18371

First action: dos2unix -f inputfile

Second action:

From the input file it can be observed that it contains blank lines, and this will cause if comparison to fail. You can put an additional check on top of your -gt 80 check to ensure before passing the variable $line its not empty using if [ ! -z $line ] or better you can put a check to ensure the line is an integer or may be both using AND.

Example:

while read line;
do
  if [[ $line =~ ^[0-9]+$ ]];then 
      if [ $line -gt 80 ];then
          echo "$line is greater then 80"
      fi
  fi
done <input_file

Or , if you do not want to put empty check([ ! -z $line ]) ,

Also, this can be done using other tools like awk in one line, but this may or may not fit in your requirement.

awk 'NF && $0>80{print $0 ,"is greater then 80"}' inputfile

Upvotes: 2

pjh
pjh

Reputation: 8064

Try this Shellcheck-clean pure Bash code:

#! /bin/bash -p

file=/root/temp1

while read -r line ; do
    (( line > 80 )) && echo "$line > 80"
done <"$file"
  • The problem with the code in the question is that it doesn't handle empty lines. This code does handle empty lines because variables containing the empty string are treated as if they contained zero in arithmetic expressions (((...))).

Upvotes: 2

Related Questions