I have need to grep an entire directory for a string, and I get about 50 results. I would like to colour each second line, either text colour or background colour. Best would be a script that I can pipe the output of any command to, and so that it spits out the same (albeit coloured) output.
+6
A:
Not very pretty but does the trick:
(save this to foo.bash and do grep whatever wherever | ./foo.bash
#!/bin/bash
while read line;
do
echo -e '\e[1;31m'$line;
read line;
echo -e '\e[1;32m'$line;
done
echo -en '\e[0m';
Here you can find the list of color codes in bash
Kimvais
2009-12-02 09:04:58
Very neat, can also be used as a function to avoid a second script.
Ludvig A Norin
2009-12-02 09:07:24
I like this, but you forgot to reset afterwards: echo -en '\e[0m';
naught101
2009-12-02 12:00:02
@naught101 good point, fixed now.
Kimvais
2009-12-02 14:21:35
Might be better to reset it after the loop.
naught101
2009-12-02 23:04:01
@naught101 another good point, fixed this too :)
Kimvais
2009-12-03 08:14:40
+2
A:
Perl is installed on many systems. You could have it alternate for you:
grep -r whatever somedir/ | perl -pe '$_ = "\033[1;29m$_\033[0m" if($. % 2)'
In Perl $.
can be substituted with $INPUT_LINE_NUMBER
if you prefer readability.
jhs
2009-12-02 09:08:02
+1
A:
and here is the same in python;
import sys
for line_number,line in enumerate(sys.stdin.readlines()):
print '%s[1;3%dm%s%s[0m' % (chr(27),(line_number % 2+1),line,chr(27)),
Kimvais
2009-12-02 09:26:24
+2
A:
This is to delineate wrapped lines I presume? This shell script uses a background color from the 256 color palette, so as not to interfere with other highlighting that grep --color might do.
#!/bin/sh
c=0
while read line; do
[ $(($c%2)) -eq 1 ] && printf "\033[48;5;60m"
printf "%s\033[0m\n" "$line"
c=$(($c+1))
done
This has the caveat that backslashes etc. within the line will be mangled, so treat this as pseudo code for reimplementation
pixelbeat
2009-12-02 11:15:39
Hah, if I had have known about --color I probably wouldn't have needed this, but both are good. Thanks for the thoughtful solution.
naught101
2009-12-02 12:03:20