Is there a method to colorize the output of cat
, the way grep
does.
For grep
, in most consoles it displays a colored output hi
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'
You may have to install pygments
using one of these:
sudo apt install python-pygments
sudo pip install pygments
sudo easy_install Pygments #for Mac user
and for highlight
package which is easily available on all distributions
sudo apt install highlight
sudo yum install highlight
I'm attaching shots for both down below for a good comparison in highlightings
Here is pygmentize
in action:
and this is highlight
:
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.
From what I understand, the binary itself is not responsible for the colors. It is the shell.
That't not correct. Terminal just interprets the color codes that is output to the terminal. Depending on its capability it can ignore certain formatting/coloring codes.
From man page it does not seem cat supports coloring its output. Even if it were to support coloring like grep what should it color in the text file? Syntax highlighting required knowledge of underlying language which is not in the scope of simple utility like cat.
You can try more powerful editors like vim,emacs, gedit etc on unix platform if seeing the code highlighted is your goal.
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'
bat precisely does that and can be aliased to cat alias cat='bat'
If you just want a one liner to set cat
output to a given color, you can append
alias cat="echo -en 'code' | cat - "
to your ~/.$(basename $SHELL)rc
Here is a gist with color codes: https://gist.github.com/chrisopedia/8754917
I like '\e[1;93m'
, which is high intensity yellow. It looks like this: