linux – How to Get Colored Content When Reading a File with Less or More

colorslesslinux

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

Best Answer

(update on 2020)

The faster way would be using less -R ref. https://superuser.com/a/117842/34893


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 add

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

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

chmod u+x ~/.lessfilter

Tested on Debian.

You get the idea. This can of course be improved further, accepting more extensions 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.