Search code examples
bashconditional-statementslogicbash-completion

bash code to count A to z char with count string input string and give output in new string


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


Solution

    • grep -o, --only-matching

      Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. Using . as pattern for every character


    grep -o . <<<"AASS"
    A
    A
    S
    S
    

    • uniq -c, --count

      prefix lines by the number of occurrences


    grep -o . <<<"AASS"|uniq -c
          2 A
          2 S
    

    • awk '{printf "%s%d", $2,$1}'

      Reorder the output. Character '$2' first then number '$1'. Print all in a single line


    grep -o . <<<"AASS"|uniq -c|awk '{printf "%s%d", $2,$1}END{print ""}'
    A2S2
    

    Unsorted alphabet

    $ string="AAASSSSFFRREEE" 
    $ grep -o . <<<"$string"|uniq -c|awk '{printf "%s%d", $2,$1}END{print ""}'
    A3S4F2R2E3
    $ string="AAASSSSFFRREEEAAAAFFFFFEE"
    A3S4F2R2E3A4F5E2
    

    Sorted alphabet

    $ string="AAASSSSFFRREEE" 
    $ grep -o . <<<"$string"|sort|uniq -c|awk '{printf "%s%d", $2,$1}END{print ""}'
    A3E3F2R2S4
    $ string="AAASSSSFFRREEEAAAAFFFFFEE"
    A7E5F7R2S4