Mikel
Mikel

Reputation: 93

Using for loop to compare two strings character by character in bash

I am writing a bash script that loops over a large file of data which i have extracted the key parts I need to use. It seems quite trivial when I was trying to do it but all I need to do is something akin to,

string1=...
string2=...    
correct=0
for i in 1..29
do
   if [string1[i] == string2[i]]
   then
      correct=correct+1
   fi
done

When I tried doing something like this I get a Bad Substitution which I assume is because some of the key's look like this,

  `41213343323455122411141331555 - key` 
  `3113314233111 22321112433111* - answer`

The spaces and occational * that are found don't need special treatment in my case, just a simple comparison of each index.

#!/bin/bash
answersCorrect=0
for i in $(nawk 'BEGIN{ for(i=1;i<=29;i++) print i}')
do
  if [ "${answer:i:1}" = "${key:i:1}" ]
   then
    answersCorrect=$answersCorrect+1 #this line#
  fi
done

I am getting no compiler errors now however I don't think i'm incrementing answersCorrect correctly. When I output it it is something like 0+1+1+1 instead of just 3 (this segment is being used inside a while loop)

Fixed Solution for that line : answersCorrect=$((answersCorrect+1))

Upvotes: 1

Views: 770

Answers (1)

Walter A
Walter A

Reputation: 20022

The original problem is fixed by comments and some extra work of @Mikel. An alternative is comparing the strings after converting the strings to lines.

diff --suppress-common-lines <(fold -w1 <<< "${string1}") <(fold -w1 <<< "${string2}") |
    grep -c "^<"

Upvotes: 1

Related Questions