Raw Input
ABC1234567890abcefghijk
Desired Output
ABC1,2,3,4,5,6,7,8,9,0,a,b,c,e,f,g,h,i,j,k
Script and Comments
Script1
[ 1] s/./&,/g
[ 2] s/^([^,]*,){3}/&\n/
[ 3] :loop
[ 4] s/,([^\n]*\n)/\1/
[ 5] t loop
[ 6] s/\n(.*),$/\1/
Comments
  1. This script and the following one first insert comma after every character, then remove unwanted ones.
  2. The `-r' option of GNU sed must be used to make sed interpret REs as EREs or you have to escape
    • every parenthesis for capturing texts or grouping REs,
    • every brace used as a quantifier.
  3. Step [1] inserts a comma after every character, then
    Steps [2] thru [6] will remove unwanted ones.
  4. Step [2] insert a newline character after the last unwanted comma, which is used as a mark.
  5. Steps [3] thru [5] constitute a loop:
    • Step [4] removes the unwanted comma farthest from and prior to the newline character.
    • If the substitution of Step [4] succeeds, Step [5] will make sed branch to Step [3] then [4] to see whether further substitution is possible.
    • Otherwise, there is no more unwanted comma prior to the newline character.
  6. Step [6] removes the comma at the end of line and the newline character, which were inserted by Step [1] and Step [2], respectively.
Script2
[ 1] s/./&,/g
[ 2] :loop
[ 3] /^[^,]{3}/!{
[ 4] s/,//
[ 5] t loop
[ 6] }
[ 7] s/,$//
Comments
  1. Steps [2] thru [6] constitute a loop, which repeats until there is no comma in the first three characters of a line.
  2. When there exists a comma in the first three characters of a line,
    • the substitution of Step [4] will succeed and
    • Step [5] will make sed branch to Step [2].