echo | sed ' s/.*/1/ :a s/$/c/ h s/[05]c.*/&buzz/ s/[0369]/333/g; s/[258]/33/g; s/[148]/3/g s/^\(333\)\+c/&fizz/ /z/{ s/.*c//; p; g; bb } g; s/c.*//; p; g :b s/c/c0123456789cx/ s/\(.\)c.*\1\(.\).*x/\2/ s/c/c0/; s/^c/1/; /c/bb ba' Or the short form: echo | sed 's/.*/1/;:a;s/$/c/;h;s/[05]c.*/&buzz/;s/[0369]/333/g;s/[258]/33/g;s/[148]/3/g;s/^\(333\)\+c/&fizz/;/z/{s/.*c//;p;g;bb};g;s/c.*//;p;g;:b;s/c/c0123456789cx/;s/\(.\)c.*\1\(.\).*x/\2/;s/c/c0/;s/^c/1/;/c/bb;ba'