When reading a file with `less` or `more`, how can I get the content in colors?

When I read a file in Linux with the command less or more, how can I get the content in colors?


If you just want to tell less to interpret color codes, use less -R. ref.


You can utilize the power of pygmentize with less - automatically! (No need to pipe by hand.)

Install pygments with your package manager or pip (possibly called python-pygments) or get it here http://pygments.org/download/.

Write a file ~/.lessfilter

#!/bin/sh
case "$1" in
    *.awk|*.groff|*.java|*.js|*.m4|*.php|*.pl|*.pm|*.pod|*.sh|\
    *.ad[asb]|*.asm|*.inc|*.[ch]|*.[ch]pp|*.[ch]xx|*.cc|*.hh|\
    *.lsp|*.l|*.pas|*.p|*.xml|*.xps|*.xsl|*.axp|*.ppd|*.pov|\
    *.diff|*.patch|*.py|*.rb|*.sql|*.ebuild|*.eclass)
        pygmentize -f 256 "$1";;

    .bashrc|.bash_aliases|.bash_environment)
        pygmentize -f 256 -l sh "$1";;

    *)
        if grep -q "#\!/bin/bash" "$1" 2> /dev/null; then
            pygmentize -f 256 -l sh "$1"
        else
            exit 1
        fi
esac

exit 0

In your .bashrc (or .zshrc or equivalent) add

export LESS='-R'
export LESSOPEN='|~/.lessfilter %s'

Also, you need to make ~/.lessfilter executable by running

chmod u+x ~/.lessfilter

Edit: If you have lesspipe on your system, you might want to use that to automatically unzip archives when looking at them with less, e.g. less log.gz. lesspipe also supports a custom .lessfilter file, so everything said above works the same, you just have to run

eval "$(lesspipe)" 

in your rc file instead of setting the LESSOPEN variable. Run echo "$(lesspipe)" to see what it does. Your .lessfilter will still work. See man lesspipe.


Tested on Debian.

You get the idea. This can of course be improved further, accepting more extensions, multiple files, or parsing the shebang for other interpreters than bash. See some of the other answers for that.

The idea came from an old blog post from the makers of Pygments, but the original post doesn't exist anymore.


Btw. you can also use this technique to show directory listings with less.


Try the following:

less -R

from man less:

-r or --raw-control-chars

Causes "raw" control characters to be displayed. (...)

-R or --RAW-CONTROL-CHARS

Like -r, but only ANSI "color" escape sequences are output in "raw" form. (...)


I got the answer in another post: Less and Grep: Getting colored results when using a pipe from grep to less

When you simply run grep --color it implies grep --color=auto which detects whether the output is a terminal and if so enables colors. However, when it detects a pipe it disables coloring. The following command:

grep --color=always "search string" * | less -R

Will always enable coloring and override the automatic detection, and you will get the color highlighting in less.

Warning: Don't put --color=always as an alias, it break things sometimes. That's why there is an --color=auto option.