3

I have two lines, which are saved in two variables. But it doesn't really matter, where they are saved. My question is, how do I compare each character from both lines?

For examples

Hello

Hlleo

result: true (H), false ... ,true (o)

Mafi
  • 129

4 Answers4

4

The following is probably what you're looking for:

l1=Hello
l2=Hlleo
count=`echo $l1|wc -m`

for cursor in `seq 1 $count`
do
    c1=`echo $l1|cut -c$cursor`
    c2=`echo $l2|cut -c$cursor`

    if test "$c1" = "$c2"
    then
        echo "true ($c1), "
    else
        echo "false ($c2 instead of $c1), "
    fi
done
2

In case both have same character length:

string_1="hello"
string_2="hilda"

for (( i=0; i<${#string_1}; i++ )); do 
    [ "${string_1:$i:1}" == "${string_2:$i:1}" ] && echo "true" || echo "false"
done
marc
  • 2,427
2

It's possible to do this in sh, but not very efficient for large strings.

compare_characters () {
  tail1="$1" tail2="$2"
  if [ "${#tail1}" -ne "${#tail2}" ]; then
    echo >&2 "The strings have different length"
    return 1
  fi
  while [ -n "$tail1" ]; do
    h1="${tail1%"${tail1#?}"}" h2="${tail2%"${tail2#?}"}"
    if [ "$h1" = "$h2" ]; then
      echo true "$h1"
    else
      echo false "$h1" "$h2"
    fi
    tail1="${tail1#?}" tail2="${tail2#?}"
  done
}

Alternatively, if you don't mind a different output format, you can use cmp -l. In a shell that has process substitution (ksh, bash or zsh):

cmp <(printf %s "$string1") <(printf %s "$string2")

Without process substitution, you need to use a workaround to pass two strings to the command: a named pipe, or write to a temporary file, or use /dev/fd if your platform supports it.

printf %s "$string1" | {
  exec 3<&0
  printf %s "$string2" | cmp /dev/fd/3 /dev/fd/0
}
0
var1="string1"
var2="string2"
i=1
l=${#var1}
while [ ${i} -le ${l} ]
do
  c1=$(echo ${var1}|cut -c ${i})
  c2=$(echo ${var2}|cut -c ${i})
  if [ ${c1} == ${c2} ]
  then
     printf "True (${c1}) "
  else
     printf "False "
  fi
  (( i++ ))
done

If the string length of the two variables are not the same, the result is ambiguous. This script assumes both variables are in the same string length.

MelBurslan
  • 6,966