Less Superpowers
You have likely used less
as a way to paginate text files or logs - a step up from cat
, which dumps the text onto the screen till the end of the file. You’ve probably also used the vi
-like search with front-slash and question-mark to search forward or backward, and “n” and “p” to move back and forth among search results.
Less can do more. Less has more superpowers that you likely haven’t tried yet.
First, let’s add some line numbers so we aren’t staring at a screen full of lines with no indication of where we are in the file.
less mycode.c
-N
Note: The “-N” is typed after opening the file in less
This now gives you line numbers. But we don’t really know how many lines are in the file, or how much more is in the file… and for this, we press =
(equals) to see a status bar at the bottom of the screen.
If there’s a huge number of log messages within a log file, you probably want to look at only the lines for a specific log level - and for that, we have “&”.
&ERROR # To show only lines containing "ERROR"
& # To show all lines
You can also get less to use a pre-processor such as, for example, replacing the word “Hello” with “Ola”:
echo "Hello" > myfile.txt
export LESSOPEN="| sed 's/Hello/Ola/' %s"
less myfile.txt
You can do more by combining this with a syntax highlighter such as pygmentize:
python3 -m pip install pygments
export LESSOPEN="| pymentize %s"
export LESS="-R" # To preserve colors from the input
less mycode.c
For this last one, we’re going to get colored line numbers by combining the abilities of cat, sed, and shell-coloring.
cat -n filename
adds line numbers to each line
sed 's/something/before&after/' filename
surrounds matching text with some strings
echo $'\033\[94mBlue\033\[0m'
changes the color to blue, displays the word “Blue”, and then resets the color
…so here it goes:
export LESSOPEN="| cat -n %s | sed 's/ *[0-9]*/'$'\033\[94m&\033\[0m/'"
export LESS="-R"
less myfile.txt