Conditional for every letter in alphabet

I wanted to know if there was a more efficient to do this. I was to setup a conditional for every letter of the alphabet, like so (I am parsing an array):

for i in "${arr[@]}"; do
if [[ $i == A* ]]; then
	echo "$i starts with A"
	else echo "$i does not start with A"
fi
done

I want to do this A-Z, is there a better way other than duplicating the if statement 26 times?

Using case statement?

1 Like

Agreed, case is a better choice.

for i in "${arr[@]}"; do
if [[ $i =~ [A-Za-z].* ]]; then
j=$i
while [[ $j =~ ...* ]]
do
 j=${j%?}
done
 echo "$i starts with $j"
	else echo "$i does not start with a letter"
fi
done

Check for a letter using regex matching in bash, the find the first character for your output.

If I understand right, the solution might be to put a for loop in a for loop (sup dawg :p):

for i in "${arr[@]}"; do
 for j in {A..Z}; do
  if [[ $i == $j* ]]; then
    echo "$i starts with $j"
    else echo "$i does not start with $j"
  fi
 done
done

That needs an enhancement for no 'does not start' messages for other letters, I bet.

Cleaner:

for i in "${arr[@]}"; do
 if [[ $i =~ [A-Za-z].* ]]; then
  j=${i:0:1}
  echo "$i starts with $j"
 else
  echo "$i does not start with a letter"
 fi
done

I seem to live in ksh systems, and can't afford to get too bash'y when doing ksh prod support and scripts.

What about

LETTERS=$(echo {A..Z})
W=Caesar
echo $W doesn\'t start with ${LETTERS/${W:0:1}}
Caesar doesn't start with A B D E F G H I J K L M N O P Q R S T U V W X Y Z