Pages

Thursday, July 13, 2017

Display File Content with Colors and Line Number Alternative to cat Ubuntu

Display File Content with Colors and Line Number Alternative to cat Ubuntu


Sometimes you may want to quickly display the contents of a file directly on the command line with the `cat` command. And sometimes the contents of that file is the source code of a program.

If you want to display the source code markup with colors and line numbers, then this trick is what you are looking for.

What you need to do first is install Pygments, a python syntax highlighter.

sudo apt-get install python-pygments python3-pygments

After installing pygments, you can now view source code with colored markups. just run the ff:

pygmentize testfile.rb

Now for the line numbers, you will have to pipe the `nl` command

pygmentize testfile.rb | nl --body-numbering=a

The option
--body-numbering
means it will accept a style for line numbering and it is any of the ff:

a - number all lines
t - number only nonempty lines
n - number no lines

I used a so that everything will be numbered including empty lines.

We can actually add nl options in bash alias so that we do not have to type it everytime.

alias nl=nl --body-number=a

While at it, lets also shorten the pygmentize command.

alias ccat=pygmentize

Now the source code syntax will be highlighted everytime we ran this command:

ccat testfile.rb | nl




No comments:

Post a Comment

Note: Only a member of this blog may post a comment.