Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash shell: Illegal number when comapring strings

Tags:

bash

shell

I am getting an error when I do string compare. Basically I am extracting names from 2 different files and try to compare them. It doesn't seem to work. Any suggestion?

 while read slave_line
 do
      slave_col1=`echo $slave_line | cut -d " " -f2`
      slave_col2=`echo $slave_line | cut -d " " -f3`
      slave_col=`echo $slave_line | cut -d " " -f1`

      while read line
      do
          master_col1=`echo $line | cut -d " " -f2`
          master_col2=`echo $line | cut -d " " -f3`
          if [ "$slave_col2" -eq  "$master_col2" ]; then
              echo $slave_col2 $master_col2 $slave_line $line
              echo $slave_line $line>> $3
       fi
       done < $2
 done < $1
like image 967
Rashmi A.P Avatar asked Jul 13 '26 15:07

Rashmi A.P


2 Answers

You say you are doing a string compare but that would be =, the operator -eq is specifically for integer comparisons.

like image 177
Ben Jackson Avatar answered Jul 15 '26 05:07

Ben Jackson


As already mentioned by Ben you're using -eq instead of = and I don't think that you're really comparing numbers.

Here is a better version of your script. I have used read instead of cut and I have also fixed your quoting.

#!/bin/bash

while read -r slave_col slave_col1 slave_col2 _
do
    while read -r _ master_col1 master_col2 _
    do
        if [ "$slave_col2" = "$master_col2" ]; then
            echo "$slave_col2 $master_col2 $slave_line $line"
            echo "$slave_line $line" >> "$3"
        fi
    done < "$2"
done < "$1"

But, as already stated by anubhava in the comments this method is very inefficient.

like image 31
Aleks-Daniel Jakimenko-A. Avatar answered Jul 15 '26 04:07

Aleks-Daniel Jakimenko-A.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!