Syntax highlighting/colorizing cat

color-scheme, syntax-highlighting, unix

Solution

`cat` with syntax highlighting is simply out of scope. `cat` is not meant for that. If you just want to have the entire content of some file coloured in some way (with the same colour for the whole file), you can make use of terminal escape sequences to control the color.

Here's a sample script that will choose the colour based on the file type (you can use something like this instead of invoking `cat` directly):

#!/bin/bash
fileType="$(file "$1" | grep -o 'text')"
if [ "$fileType" == 'text' ]; then
    echo -en "\033[1m"
else
    echo -en "\033[31m"
fi
cat $1
echo -en "\033[0m"

The above (on a terminal that supports those escape sequences) will print any text file as 'bold', and will print any binary file as red. You can use `strings` instead of `cat` for printing binary files and you can enhance the logic to make it suit your needs.

Problem

Is there a method to colorize the output of `cat`, the way `grep` does. For `grep`, in most consoles it displays a colored output highlighting the searched keywords. Otherwise, you can force it by calling `grep --color` Is there a generic way to color the output of any program according to your personal choice. From what I understand, the program itself is not responsible for the colors. It is the shell. I am using the default shell in FreeBSD 5.2.1 which looks like it has never seen colors since epoch.

Original source