0

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] =
John Kugelman
  • 349,597
  • 67
  • 533
  • 578

1 Answers1

0

A better way to append an element to an array is with array+=(...). Then you don't have to worry about having the correct index on the left-hand side.

alpha+=("${string[i]}")
num+=("${string[i]}" "${string[i+1]}")
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Thank You for the solution. But am afraid it doesn't resolve the problem completely. `Enter your alphanumeric string: v4b3 num[0] = 4 num[1] = 3 alpha[0] = v alpha[1] = b vvvvbbb **$ sh Q1.sh** Enter your alphanumeric string: a12b20 num[0] = 1 num[1] = 2 num[2] = 2 num[3] = 0 alpha[0] = a alpha[1] = b abb` – Bharath G Kumar Mar 30 '20 at 13:31
  • Handling two-digit numbers is a different question. – John Kugelman Mar 30 '20 at 13:38
  • It would be great then, if you could help me with that too. Thank You. – Bharath G Kumar Mar 30 '20 at 13:39
  • I recommend posting it as a separate question. It requires a different, more complicated answer, and Stack Overflow isn't designed for back-and-forth debugging sessions tackling multiple problems. – John Kugelman Mar 30 '20 at 13:48