Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I'd like the terminal to alternate the background color on successive lines, making it easier to see where one starts and the next one ends. This would be specially useful when reading logs with tail -f, but, I'd prefer a solution that works all the time. Specially if it's something I can use with Terminator, though I'd be willing to use a different terminal if it has this functionality.

share|improve this question

1 Answer 1

Might need a custom terminal to get this sort of functionality in all circumstances but for things like tail -f the following python3 script should work:

#!/usr/bin/python3

import shutil
import sys

try:
  from termcolor import cprint
except:
  print("Error: please install the python3-termcolor package")
  sys.exit(1)

def expandtabs(line):
  """Tabs don't seem to be highlighted so expand them to spaces"""
  result = ""
  col = 0
  for c in line:
    if c == "\t":
      next_col = 8 * ((col // 8) + 1)
      result += " " * (next_col - col)
      col = next_col
    else:
      result += c
      col += 1
  return result

def pad(line, n):
  """Pad a line until it is a multiple of n, to avoid jagged highlighting"""
  while (len(line) % n) != 0:
    line += " "
  return line

# Get the width of the terminal
cols, rows = shutil.get_terminal_size()

try:
  odd = True
  for line in sys.stdin:
    if odd:
      cprint(pad(expandtabs(line.rstrip()), cols), "white", "on_grey")
    else:
      cprint(pad(expandtabs(line.rstrip()), cols), "grey", "on_white")
    odd = not odd
except KeyboardInterrupt:
  sys.exit(0)

If saved as zebra.py someplace in your path, it can be added to commands such as:

cat /proc/cpuinfo | zebra.py
tail -f /var/log/kern.log | zebra.py

It requires the python3-termcolor package and at least Python 3.3 to use the shutil.get_terminal_size function. There is plenty of room for improvement, could try the python3-xtermcolor package to gain more than just the few colors at https://pypi.python.org/pypi/termcolor, add functionality to read files from the command line instead of just stdin, etc.

I'm not sure it makes output much easier to read, but it certainly looks neat.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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