Mohamed Nuzhy Mohamed Nuzhy - 3 months ago 12
Bash Question

If statement for two different arrays in bash

I have two arrays, which are arrAlpha[] and arrPT[]. Array arrAlpha contains the Alphabets and array arrPT[] contains some of the plain letters.following is the code that i wrote in bash shell script to compare elements of both arrays and to store the position elements of arrPT[] in arrAlpha[] to array arrT[]. But when i run i feel like something is wrong in if statement to print out the elements in arrT[]. can anyone help me please?

#!/bin/bash

arrAlpha=(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)

arrPT=(E K N R S W )
lenPT=${#arrPT}
declare -A arrT
q=0
for((i=0; i<lenPT; i++)) do
for((j=i; j<26; j++)) do
if [ ${arrPT[$i]} = ${arrAlpha[$j]} ]; then
arrT[$q]=$j % 26;
((++q));
fi
done
done

echo ${arrAlpha[@]}
echo ${arrPT[@]}
echo ${arrT[@]}


the expected output is to change elements arrPT to number 0 to 25.

arrAlpha=(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)
arrPT =(E K N R S W)
arrT =(4 10 13 17 18 22)

Answer

Here's a fixed version of your script - there are some style changes that I prefer

arrAlpha=(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)
arrPT=(E K N R S W )
# array length needs index *
lenPT=${#arrPT[*]}
# seems arrT can be simple indexed array
declare -a arrT
q=0
for((i=0; i<lenPT; ++i)); do
  for((j=0; j<26; ++j)); do
    if [[ ${arrPT[i]} == ${arrAlpha[j]} ]]; then
# arithmetic inside $(())
      arrT[q++]=$((j % 26))
    fi
  done
done
echo ${arrAlpha[@]}
echo ${arrPT[@]}
echo ${arrT[@]}