Syntax highlighting/colorizing cat

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.


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 "33[1m"
else
    echo -en "33[31m"
fi
cat $1
echo -en "33[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.


I'd recommend pygmentize from the python package python-pygments . You may want to define the following handy alias (unless you use ccat from the ccrypt package).

alias ccat='pygmentize -g'

And if you want line numbers:

alias ccat='pygmentize -g -O style=colorful,linenos=1'

Options:

pygmentize is good. I have an alias:

alias c='pygmentize -g'

but highlight is another widely available alternative is

alias cats='highlight -O ansi --force'

Installation:

You may have to install pygments using:

sudo pip install pygments
sudo easy_install Pygments #for Mac user

and for highlight package which is easily available on all distributions

sudo apt-get install highlight
sudo yum install highlight
  • Bitbucket repo: https://bitbucket.org/birkenfeld/pygments-main
  • GitHub mirror: https://github.com/sglyon/pygments
  • In Action:

    I'm attaching shots for both down below for a good comparison in highlightings

    Here is pygmentize in action: pygmentize突出显示python文件

    and this is highlight : 高亮突出显示python文件

    链接地址: http://www.djcxy.com/p/8264.html

    上一篇: 从命令行打印JSON? (来自文件)

    下一篇: 语法突出显示/着色cat