I need help on creating a shell script which will take input string and expand as below:
Input => output
A2B3C4 => AABBBCCCC
I need help on creating a shell script which will take input string and expand as below:
Input => output
A2B3C4 => AABBBCCCC
$ perl -e 'my @F=split //, shift;
for my $i (0..@F) { print $F[$i] x $F[++$i]};
print "\n"' A2B3C4
AABBBCCCC
This splits the input so that each single character becomes an element in an array (@F). Then, using perl's string multiplier operator (x) it prints every even-numbered element (starting at 0) a number of times equal to the next odd-numbered element.
or if you want it to take input from stdin rather than the command line:
$ echo $'A2B3C4\nE5F2G7' | perl -ne 'my @F=split //;
for my $i (0..@F) { print $F[$i] x $F[++$i]};
print "\n"'
AABBBCCCC
EEEEEFFGGGGGGG
Both of these implementations have the flaw that it only allows single-digit strings and single-digit counts.
The following removes that limitation:
$ echo A12B3CZ4 | perl -ne '
# insert a space between numbers and alphabetic characters.
s/([[:alpha:]])(\d)/$1 $2/g;
s/(\d)([[:alpha:]])/$1 $2/g;
# split on spaces
@F = split / /;
for my $i (0..@F) { print $F[$i] x $F[++$i]};
print "\n"'
AAAAAAAAAAAABBBCZCZCZCZ
With Perl you can make it like as shown:
echo a2b3c4 |
perl -pe 's/(\D)(\d+)/$1x$2/ge'
aabbbcccc
Easy shell implementation:
#!/usr/bin/env bash
char=""
count=""
echo "$1" | while read -n1 -r c; do
if [ "$char" = "" ]
then
char="$c"
continue
fi
if [ "$count" = "" ]
then
count="$c"
for i in $(seq 1 "$count")
do
printf "%s" "$char"
done
char=""
count=""
continue
fi
done
printf "\n"
Example:
$ ./transform.sh A2B3C4D0E1
AABBBCCCCE
It doesn't work with numbers bigger than 9 though. One would have to implement some larger logic to distinguish between letters and numbers.