-5

I need to get desired output using a shell script.

Input:

aaabbcaaabbcc  

Desired Output:

a3b2ca3b2c2  

Command should print number of occurrence of each alphabet only when it's greater than 1, i.e aaab should come as a3b.

I tried with below commands and they didn't work for me, as I have to pass characters manually to my command.

echo "aaabbcaaabbcc" | grep -o a  
echo "aaabbcaaabbcc" | uniq -c  
echo "aaabbcaaabbcc" | grep -o a | uniq -c  

I am unable to find how I can split it character-wise and then check number of occurrences.

closed as unclear what you're asking by Kusalananda, JdeBP, Jeff Schaller, jimmij, Mr Shunz Mar 23 at 12:19

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1) Where is the input coming from? Is it the contents of a text file? The output of a command or application? 2) What have you tried to do? If you just want to replace the string in the input with the string in the desired output then you don't need a shell script. Have a look at the sed command. – Nasir Riley Mar 23 at 10:06
  • 1
    You seem to want to implement some form run-length encoding. What issues are you having with doing this? – Kusalananda Mar 23 at 10:11
  • There are far too many possible answers with this incomplete and underspecified question, starting with echo a3b2ca3b2c2. – JdeBP Mar 23 at 10:12
  • 2
  • 1
    @Machine Run-length encoding (RLE) is a well known and simple way of compressing highly redundant data. If you have a particular issue with the awk variant on the Rosetta page that I linked to, then you may want to ask another question about it. Pure programming questions relating to the implementation of specific algorithms would arguably be more suitable on StackOverflow though. – Kusalananda Mar 25 at 13:12
2
str="aaabbcaaabbcc"

echo $str | fold -w1 | uniq -c | \
while read count char; do
  if [ $count -gt 1 ]; then
    printf "$char$count"
  else
    printf "$char"
  fi
done

a3b2ca3b2c2

  • 1
    There seems to be a special case for $count -eq 1 – nohillside Mar 23 at 10:17
  • 1
    Indeed. Fixed for that case. – Fedor Dikarev Mar 23 at 10:21
  • This would unfortunately fail if the string contained backslashes or percentage signs, or filename globbing patterns, or started with a dash, or if IFS was set to a set of digits or letters. – Kusalananda Mar 23 at 10:41
  • @ Fedor Dikarev , I never knew about fold which can split a word vertically in char form. Thanks for this – Machine Mar 25 at 12:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.