2
\$\begingroup\$

I have a script:

$ cat ~/zebra.pl
#!/bin/perl
use Term::ANSIColor;

$Term::ANSIColor::EACHLINE = "\n";

my $zebra = 1; # Are zebras black with white stripes, or white with black stripes?!

my $black = color('white on_black');
my $blue = color('white on_blue');

while (<>){
    chomp($_);

    $zebra = $zebra == 1 ? 0 : 1;

    ($zebra == 1 && print $blue) || print $black;

    print $_;

    ($zebra == 1 && print $black) || print $blue;

    print "\n";
}

print color('reset');

Usage:

some-command | zebra

The output consists of alternating lines that have black and blue backgrounds, respectively. The script seems needlessly long and complex. I'm wondering how much shorter it could be.

\$\endgroup\$
1
  • 3
    \$\begingroup\$ Actually Perl also can do it in 31 characters: some-command | perl -pe '$_="\e[4".$.%2*4 .";37m$_\e[m"'. So I can't really see where the actual challenge is. \$\endgroup\$
    – manatwork
    Apr 9 '13 at 15:47
4
\$\begingroup\$

Sed: 45 characters

1~2s/^/\e[40;37m/;2~2s/^/\e[44;37m/;s/$/\e[m/

Usage:

some-command | sed $'1~2s/^/\e[40;37m/;2~2s/^/\e[44;37m/;s/$/\e[m/'
\$\endgroup\$
1
\$\begingroup\$

C#: 105 84

Easy. You just need some sort of marker, and your infinite loop. From there, things are rather easy.

(Assumes using System;, this is just a method body.)

bool b=false;while(true){Console.WriteLine((b?"Blue":"Black")+" background!");b=!b;}
\$\endgroup\$
1
  • \$\begingroup\$ You can tweak one more byte with b=1==0; ;) \$\endgroup\$ May 1 '17 at 19:29
1
\$\begingroup\$

Awk: 56 52 characters

{x="\x1b[37;4";y=NR%2;print x (y?0:4)"m"$0x 4*y"m"}

{x="\x1b[37;4%dm";printf x"%s"x"\n",NR%2?0:4,$0,NR%2*4}

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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