-1

I have files that contain 2 numbers like the following:

File 1

1
0

File 2

0
1

File 3

3
3

I want to compare the number on the first line to the number on the second line. If the number on the first line is higher echo : Higher If the number on the first line is lower echo : Lower If the number on both lines are the same echo : Same

How can i acheive this?

  • Hello! What have you tried? How did it not work as expected or intended? – DopeGhoti Apr 23 at 22:12
  • I have tried to use an if statement that checks using: echo "a=$a"; echo "b=$b"; if [ $a \> $b ]; however i am not sure how to set each number in the files to a and b – jonny b Apr 23 at 22:18
1

Loop over the files. For each file, read the two numbers, then compare them:

for file in file1 file2 file3; do
    { read num1; read num2; } <"$file"
    if [ "$num1" -gt "$num2" ]; then
        echo Higher
    elif [ "$num1" -lt "$num2" ]; then
        echo Lower
    else
        echo Same
    fi
done

Arithmetic comparison in the shell is done with -gt and -lt. The other arithmetic comparison operators are -ge, -le and -eq. See man test. The operators < and > will test for lexicographical ordering, and will not be what you want to use here.

Or, with awk:

awk -v RS='' -F '\n' '{ print ($1 > $2 ? "Higher" : ($1 < $2 ? "Lower" : "Same")) }' file1 file2 file3

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.