I want to write a shell script to get the following output:
$ Enter String: a2b3
aabbb
I've used arrays within for
loops, but it always fails to append two-digit values from the string, as a single element into the array. It always gets stored as two separate elements in the array.
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+=("${string[i]}")
elif [[ ${string[i]} =~ [0-9] ]]
then
if [[ ${string[i+1]} =~ [0-9] ]]
then
num+=${string[i]}${string[i+1]}
elif ! [[ ${string[i+1]} =~ [0-9] ]]
then
num+=("${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
n=${#alpha[*]}
for (( i=0;i<n;i++ ))
do
y=${num[i]}
for (( j=0;j<y;j++ ))
do
echo -ne ${alpha[i]}
done
done
echo " "
The output I get for the same:
$ 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
I need the value 12
to be stored as a single element num[0]
rather than as two individual elements, num[0]=1
, num[1]=2
. Same with the value 20
.
Please help me out here....thank you in advance.