jbailie1991
jbailie1991

Reputation: 1345

Integer expression expected error for each loop in script

The following:

dest=$1
while read -r line
do
    num=$(grep -o "[0-9]" <<< "$line")
    if [ "$num" -gt 1 ]; then
        echo "$line" 
    fi
done < "$dest"

This is mean to print out the line with a leading digit greater than 1, but instead prints a random integer, with most cases stating integer expression expected.

The file being read in and looped over contains lines which all start with number, followed by a space and a sentence:

3 overflow-x
4 font-size
....etc

Is there something I'm doing wrong in the if statement? is there a way to convert the digit into an actual number type instead of doing string comparisons?

Upvotes: 1

Views: 209

Answers (2)

anubhava
anubhava

Reputation: 784918

Actually you should seriously consider using this short & simple awk command instead of while loop, grep and if condition script:

awk '$1>1' file
3 overflow-x
4 font-size

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174696

You need to use anchor to match the number present at the start.

num=$(grep -o '^[0-9]\+' <<< "$line")

Upvotes: 0

Related Questions