I want to write a shell script to get the following output:
$ Enter String: a2b3
aabbb
I tried using for
loops and arrays, but the loop count messes with the array index and leaves null elements within the array, making it impossible to print out the array as required.
The script used:
echo "Enter your alphanumeric string: "
read a
n=${#a}
for (( i=0;i<n;i++ ))
do
string[i]=${a:i:1}
if [[ ${string[i]} =~ [a-zA-Z] ]]
then
alpha[i]=${string[i]}
elif [[ ${string[i]} =~ [0-9] ]]
then
if [[ ${string[i+1]} =~ [0-9] ]]
then
num[i]=${string[i]}${string[i+1]}
elif ! [[ ${string[i+1]} =~ [0-9] ]]
then
num[i]=${string[i]}
fi
fi
done
n=${#num[*]}
for (( i=0;i<n;i++ ))
do
echo num[$i] = ${num[i]}
done
n=${#alpha[*]}
for (( i=0;i<n;i++ ))
do
echo alpha[$i] = ${alpha[i]}
done
The output I get for the same:
$ sh Q1.sh
Enter your alphanumeric string:
a6b3
num[0] =
num[1] = 6
alpha[0] = a
alpha[1] =