Hi folks just started write code in bash but stuck in my own question in want to count a to alphabets repetation in string like
read -p 'enter the string' str # SUPPOSE STRING USER ENTER IS
input = AAASSSSFFRREEE
i wanna get output like= A3S4F2R2E3
what can i do i am trying with for condition and this program is making monkey out of me
CodePudding user response:
One solution could be to loop over the string and strip away the first characters while counting them.
Example:
#!/bin/bash
IFS='' read -rp 'enter the string: ' str
res=''
# loop while the string is not empty
while [[ -n $str ]]
do
# get the first character
ch=${str:0:1}
# create a regex matching the start of the string,
# on one or more of the first character
regex="^($ch )"
# perform the regex matching
[[ "$str" =~ $regex ]]
# the matching string
match="${BASH_REMATCH[1]}"
# concatenate the character the count to the result
res="$res$ch${#match}"
# remove the matching characters from the string
str=${str#"$match"}
done
# print the result
printf "%s\n" "$res"
Examples:
Input | Output |
---|---|
AAASSSSFFRREEE |
A3S4F2R2E3 |
AAASSSSFFRREEEAAAFFFFFEE |
A3S4F2R2E3A3F5E2 |
CodePudding user response:
Unsorted alphabet
$ string="AAASSSSFFRREEE"
$ grep -o . <<<"$string"|uniq -c|awk '{printf "%s%d", $2,$1}'
A3S4F2R2E3
$ string="AAASSSSFFRREEEAAAAFFFFFEE"
A3S4F2R2E3A4F5E2
Sorted alphabet
$ string="AAASSSSFFRREEE"
$ grep -o . <<<"$string"|sort|uniq -c|awk '{printf "%s%d", $2,$1}'
A3E3F2R2S4
$ string="AAASSSSFFRREEEAAAAFFFFFEE"
A7E5F7R2S4