428
139
When I read a file in Linux with the command less
or more
, how can I get the content in colors?
428
139
When I read a file in Linux with the command less
or more
, how can I get the content in colors?
156
(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.
7@puk you can do something like ls --color=always -l | less -R
. Obviously a lot to type but you could alias it to something like ll
. That is if you don't want to use any extra libraries. – PhilT – 2014-07-23T16:17:57.523
The -g flag on pygmentize will solve the problem of "Error: no lexer for filename" for filetypes not included, as described here http://askubuntu.com/a/392017/115392
– Pan Chrono – 2014-09-02T12:37:24.9402added @SergiyByelozyorov's comment into the answer. – andrybak – 2015-01-18T12:54:06.430
Just in case anyone is interested, I wrote a pair of scripts that serves a very similar purpose (pygmentize-addons). They are wrappers around pygmentize
, used to view syntax highlighted code for files or scripts on PATH via stdout, less
, or PNG image. I use it all the time to examine source code of files and installed scripts.
dont forget to sudo aptitude install python-pygments
– arod – 2015-07-09T19:03:08.980
is there an easy way to obtain more saturated colors on the default color scheme (php) to view in console? – arod – 2015-07-10T00:46:18.797
2My edit was rejected so I guess I'll post it as a comment instead: Don't test the exit codes of commands indirectly. You can use if grep -q "#\!/bin/bash" "$1"
(the -q
suppresses standard output). You may want to redirect standard error with 2>/dev/null
. – Tom Fenech – 2015-10-23T13:16:38.333
@TomFenech good point, I edited the answer accordingly. – Dario Seidl – 2018-11-11T15:43:25.403
It took me a long time to troubleshoot back to this, after noticing less
could no longer decompress .gz,bz2,xz,etc. files on the fly. How to have both color and prior LESSPIPE features? – Marcos – 2019-01-14T13:54:44.190
1To get a list of all unique file extensions supported by your currently installed pygmentize version, in a format suitable for pasting into this .lessfilter script, run pygmentize -L | grep -o "(filenames .*)" | sed -E "s,\(filenames (.*)\),\1,gm;s/, /\n/g" | sort -u | tr "\n" "|"
. Note that on certain Linuxes, setting LESSOPEN
may not be necessary because it is already setup to use lesspipe
which detects the .lessfilter file already (run echo $LESSOPEN
to check). – Bart – 2019-05-17T09:38:31.877
6
If you want to have coloring of the source code files, you also need to make ~/.lessfilter executable by running chmod u+x ~/.lessfilter
. You also need to have pygmentize (http://pygments.org/download/) installed.
Can anyone confirm that this works as it has no effect for me when I execute a command like ls -l | less
– puk – 2013-10-30T13:59:25.547
Any idea how to chain this with Vladimir Linek's lessopen.sh?? it is setup with this form: LESSOPEN="lessopen.sh %s" – Gregory – 2013-12-23T05:12:22.357
520
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. (...)
it does not work
there is some conf file for "less" like for vim there is .vimrc ? – Open the way – 2010-03-09T10:59:02.137
Very useful combined with unbuffer
– Claudiu – 2015-06-22T23:09:47.043
18You can also type -R
when you already opened less
to achieve this. – Scz – 2016-09-01T07:56:57.770
3IMHO this should actually be the accepted answer, it is much more simple – Willian Mitsuda – 2017-04-05T07:14:09.643
As Nitrodist said this is useful only if tte escape codes for coloring are present. So if you want the git diff's output in less, you have to use git diff --color | less -R – Rohit Walavalkar – 2018-02-19T12:16:02.993
2This worked for me with grep only when I included the --color=always
option in grep.: grep --color=always foo myfile.txt | less -R
– Dannid – 2019-01-14T17:31:34.153
cool and should-be accepted one to me – Nam G VU – 2020-01-15T03:56:37.627
17This is useful when the file itself contains the escape codes that will need to be displayed. – Nitrodist – 2011-12-16T21:16:45.103
interesting, a test for less
file contains escape characters: script
ls --color
exit
less -R typedscript
– LiuYan 刘研 – 2013-03-12T08:02:20.180
1I used to know about less -r but searching in the file using "/" kept bringing up the wrong lines. -R seems to do a better job. Thanks for the tip. – Amos Shapira – 2013-08-06T00:28:56.507
54It should be noted that most programs use the isatty(2)
syscall to check whether their standard output is a terminal, and usually disable colorized output if it is not. For any pipe to less, isatty
will return 0. To check whether this works, try echo -e '\x1b[32;1mtest\x1b[m' | less -r
– mic_e – 2013-09-24T22:53:35.503
Using the lower case '-r' for me means that the ^M characters from windows files are not shown. I like this because I'm not bothered about line endings and it makes the rest of the output a bit clearer. – J.Churchill – 2013-09-30T08:48:20.310
11This answer does not excel in the actually does something test. – Michael Wolf – 2014-05-09T22:24:18.463
141
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 impliesgrep --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.
2Is there anyway to let grep know just pipe less -R command and then just do coloring? So, we don't have to put --color=always and less -R all the time. – A-letubby – 2015-02-27T07:50:24.577
1This is by far the simplest working answer. Thanks! – Danny Staple – 2015-10-03T11:16:16.100
1This also works when you need to pipe git diff
to less
. Doing just this: git diff | less
won't show you any colors. You need to do this instead: git diff --colors=always | less
or git diff --colors=always some_file | less
. (I'm using cygwin on Windows 10, by the way.) – CSCH – 2018-08-27T20:17:32.883
6Nice, thanks. Except that I need to use -R
as an option to less
, as well. – naught101 – 2012-05-08T06:41:10.183
10I believe grep -R
is for specifying recursive search. less -R
is necessary for less
to correctly spit the colors back out. grep --color=always [grep cmds] | less -R
works for me on OS X 10.7.3! – Steven Lu – 2012-05-09T13:56:46.350
@naught101 @Steven Lu Edited in, though it seems that some people may not need to use less -R
(according to the author of the original post, anyway). – jtpereyda – 2013-10-22T17:17:02.740
36
Use view
instead of less
. It opens the file with vim
in readonly mode.
It's practically a coloured less
: a pager where you can search with / (and more). The only drawback is that you can't exit with q but you need :q
Also, you get the same colouring as vim
(since you're in fact using vim
).
1I upvoted (I didn't know about view
) but another downside is that j/k/up/down don't instantly scroll, since there is a cursor. – Tyler Collier – 2015-03-01T17:38:46.897
7Note that you may need to add view -
when piping – user45909 – 2015-03-02T00:54:48.637
7vim
is an editor, which loads the complete file into memory, whereas less
is a pager, loading the file only partially into memory. You will know the difference with huge files. – sjas – 2016-07-20T12:13:45.540
1@RiccardoGalli - Cool idea, but i would agree about the performance concern, it's not instantaneous. When viewing huge logs or greps, especially over-the-line (SSH), less
is faster since it's not dumping the entire output line by line via "inserts" into vim
. Also, you can search with less
using '/'. Additionally it has a "tail" mode using shift-F which is handy. – dhaupin – 2016-09-29T17:49:15.813
gmic -h | view
starts to execute vim
commands. It is not safe. gmic -h | view -
doesn't color on Ubuntu 18.10, so downvoting. – anatoly techtonik – 2018-09-24T11:39:35.380
at least on debian, view
is a Debian Alternative, that is, /usr/bin/view
points to /etc/alternatives/view
. Try sudo update-alternatives --config view
.
ls --color=always > /tmp/file && view /tmp/file
certainly does not work.... It shows the escape codes instead of rendering them. – Gert van den Berg – 2019-07-05T10:24:00.017
How about the performance of big files? Vim syntax highlighting is know to be slow on huge files. – pihentagy – 2014-02-20T10:28:14.197
I don't know what's your value for 'big', but opening a ~10000 lines file is instantaneous, search inside included. – Riccardo Galli – 2014-02-20T11:50:50.483
18
To tell less to show colors call it with -R:
less -R
Unfortunately some programs detect that their stdout is not a terminal and disable colors - e.g pacman (Arch Linux package manager).
In those cases its possible to use unbuffer
:
unbuffer <command> | less -R
Example using pacman
unbuffer pacman -Ss firefox | less -R
The unbuffer
command is usually part of the package expect
(Arch Linux, Debian/Ubuntu) or expect-dev
(legacy versions of Debian/Ubuntu).
To answer the question for completeness:
As others already answered, pygmentize
is great for colorizing source code. It does not require unbuffer
. Easiest call:
pygmentize someSource.cpp | less -R
2To use unbuffer
on Ubuntu, sudo apt install expect
– wisbucky – 2018-12-04T18:37:41.653
This answer needs more upvotes. – Thomas Dignan – 2019-04-19T14:26:28.740
I was trying to pipe dmesg output to check on boot errors but the colours didn't work unless I use unbuffer, which was confusing the heck out of me: unbuffer dmesg | less -R
works as expected. – pbhj – 2019-05-12T09:49:58.253
on macOS brew install expect
gets you the necessary unbuffer
command. – luckman212 – 2019-10-19T20:30:48.997
15
pygmentize
supports the -g
option to automatically guess the lexer to be used which is useful for files read from STDIN
without checking any extension type.
Using that, you only need to set the following 2 exports in your .bashrc
without any additional scripts:
export LESS='-R'
export LESSOPEN='|pygmentize -g %s'
4Concise and effective. I prefer defining an alias, because sometimes less is better. So: alias lesc='LESS="-R" LESSOPEN="|pygmentize -g %s" less' – Tiago – 2014-04-28T18:27:09.240
10
You didn't say what this color should mean, e.g. what should the colors be for a text file?
If what you want is syntax highlighting for source code, you need a source code highlighter. I sometimes use pygmentize like this
pygmentize file.cpp | less
or
pygmentize file.cpp | more
There are other highlighters around.
This is pretty fast. If you don't mind firing up vim
there is a read-only mode that can give you syntax highlighting if you have it in vim
.
view file.cpp
or alternatively see churnd's answer.
6
This is yet another pygments-based answer, with several major improvements:
lesspipe
or lessfile
filtersless
sudo apt-get install python-pygments python3-pygments gawk
Check whether lesspipe
or lessfile
is already enabled:
echo $LESSOPEN
If you don't see either program referenced there, ensure that lesspipe
is installed (most distros come with it).
Add the following to ~/.bashrc
:
# sets LESSOPEN and LESSCLOSE variables
eval "$(SHELL=/bin/sh lesspipe)"
# interpret color characters
export LESS='-R'
# to list available styles: `pygmentize -L styles`
export PYGMENTIZE_STYLE='paraiso-dark'
# optional
alias ls='ls --color=always'
alias grep='grep --color=always'
If you don't want lesspipe
, replace the eval
statement with:
export LESSOPEN='|~/.lessfilter %s'
~/.lessfilter
Add the following code and make the file executable: chmod u+x ~/.lessfilter
#!/bin/bash
for path in "$@"; do
# match by known filenames
filename=$(basename "$path")
case "$filename" in
.bashrc|bash.bashrc|.bash_aliases|.bash_environment|.bash_profile|\
.bash_login|.bash_logout|.profile|.zshrc|.zprofile|.zshrc|.zlogin|\
.zlogout|zshrc|zprofile|zshrc|zlogin|zlogout|.cshrc|.cshdirs|\
csh.cshrc|csh.login|csh.logout|.tcshrc|.kshrc|ksh.kshrc)
# shell lexer
pygmentize -f 256 -O style=$PYGMENTIZE_STYLE -l sh "$path"
;;
.htaccess|apache.conf|apache2.conf|Dockerfile|Kconfig|external.in*|\
standard-modules.in|nginx.conf|pacman.conf|squid.conf|termcap|\
termcap.src|terminfo|terminfo.src|control|sources.list|CMakeLists.txt|\
Makefile|makefile|Makefile.*|GNUmakefile|SConstruct|SConscript|\
.Rhistory|.Rprofile|.Renviron|Rakefile|Gemfile|PKGBUILD|autohandler|\
dhandler|autodelegate|.vimrc|.exrc|.gvimrc|vimrc|exrc|gvimrc|todo.txt)
# filename recognized
pygmentize -f 256 -O style=$PYGMENTIZE_STYLE "$path"
;;
*)
ext=$([[ "$filename" = *.* ]] && echo ".${filename##*.}" || echo '')
case "$ext" in
.as|.mxml|.bc|.g|.gd|.gi|.gap|.nb|.cdf|.nbp|.ma|.mu|.at|.run|\
.apl|.adl|.adls|.adlf|.adlx|.cadl|.odin|.c-objdump|.s|\
.cpp-objdump|.c++-objdump|.cxx-objdump|.d-objdump|.S|.hsail|\
.ll|.asm|.ASM|.objdump-intel|.objdump|.tasm|.au3|.ahk|.ahkl|\
.bb|.decls|.bmx|.bas|.monkey|.BAS|.bst|.bib|.abap|.ABAP|.cbl|\
.CBL|.cob|.COB|.cpy|.CPY|.gdc|.maql|.p|.cls|.c|.h|.idc|.cpp|\
.hpp|.c++|.h++|.cc|.hh|.cxx|.hxx|.C|.H|.cp|.CPP|.ino|.clay|\
.cu|.cuh|.ec|.eh|.mq4|.mq5|.mqh|.nc|.pike|.pmod|.swg|.i|.vala|\
.vapi|.capnp|.chpl|.icl|.dcl|.cf|.docker|.ini|.cfg|.inf|\
.pc|.properties|.reg|.tf|.pypylog|.cr|.csd|.orc|.sco|.css|\
.less|.sass|.scss|.croc|.d|.di|.smali|.jsonld|.json|.yaml|\
.yml|.dpatch|.darcspatch|.diff|.patch|.wdiff|.boo|.aspx|.asax|\
.ascx|.ashx|.asmx|.axd|.cs|.fs|.fsi|.n|.vb|.als|.bro|.crmsh|\
.pcmk|.msc|.pan|.proto|.pp|.rsl|.sbl|.thrift|.rpf|\
.dylan-console|.dylan|.dyl|.intr|.lid|.hdp|.ecl|.e|.elm|.ex|\
.exs|.erl|.hrl|.es|.escript|.erl-sh|.aheui|.befunge|.bf|.b|\
.camkes|.idl4|.cdl|.cw|.factor|.fan|.flx|.flxh|.frt|.f|.F|\
.f03|.f90|.F03|.F90|.PRG|.prg|.go|.abnf|.bnf|.jsgf|.cyp|\
.cypher|.asy|.vert|.frag|.geo|.plot|.plt|.ps|.eps|.pov|.inc|\
.agda|.cry|.hs|.idr|.kk|.kki|.lagda|.lcry|.lhs|.lidr|.hx|\
.hxsl|.hxml|.sv|.svh|.v|.vhdl|.vhd|.dtd|.haml|.html|.htm|\
.xhtml|.xslt|.pug|.jade|.scaml|.xml|.xsl|.rss|.xsd|.wsdl|\
.wsf|.xpl|.pro|.ipf|.nsi|.nsh|.spec|.i6t|.ni|.i7x|.t|.io|\
.ijs|.coffee|.dart|.eg|.js|.jsm|.juttle|.kal|.lasso|\
.lasso[89]|.ls|.mask|.j|.ts|.tsx|.jl|.aj|.ceylon|.clj|\
.cljs|.golo|.gs|.gsx|.gsp|.vark|.gst|.groovy|.gradle|.ik|\
.java|.kt|.pig|.scala|.xtend|.cpsa|.cl|.lisp|.el|.hy|.lsp|.nl|\
.kif|.rkt|.rktd|.rktl|.scm|.ss|.shen|.xtm|.cmake|.mak|.mk|\
.[1234567]|.man|.md|.css.in|.js.in|.xul.in|.rst|.rest|.tex|\
.aux|.toc|.m|.sci|.sce|.tst|.ml|.mli|.mll|.mly|.opa|.sml|.sig|\
.fun|.bug|.jag|.mo|.stan|.def|.mod|.mt|.ncl|.nim|.nimrod|.nit|\
.nix|.cps|.x|.xi|.xm|.xmi|.mm|.swift|.ooc|.psi|.psl|.G|.ebnf|\
.rl|.treetop|.tt|.adb|.ads|.ada|.pas|.dpr|.pwn|.sp|.pl|.pm|\
.nqp|.p6|.6pl|.p6l|.pl6|.6pm|.p6m|.pm6|.php|.php[345]|.zep|\
.praat|.proc|.psc|.lgt|.logtalk|.prolog|.pyx|.pxd|.pxi|.dg|\
.py3tb|.py|.pyw|.sc|.tac|.sage|.pytb|.qvto|.Rout|.Rd|.R|.rq|\
.sparql|.ttl|.r|.r3|.reb|.red|.reds|.txt|.rnc|.graph|\
.instances|.robot|.fy|.fancypack|.rb|.rbw|.rake|.gemspec|\
.rbx|.duby|.rs|.rs.in|.SAS|.sas|.applescript|.chai|.ezt|\
.mac|.hyb|.jcl|.lsl|.lua|.wlua|.moo|.moon|.rexx|.rex|.rx|\
.arexx|.sh|.ksh|.bash|.ebuild|.eclass|.exheres-0|.exlib|.zsh|\
.sh-session|.shell-session|.bat|.cmd|.fish|.load|.ps1|.psm1|\
.tcsh|.csh|.ns2|.st|.smv|.snobol|.rql|.sql|.sqlite3-console|\
.do|.ado|.scd|.tcl|.rvt|.ng2|.tmpl|.spt|.cfc|.cfm|.cfml|\
.evoque|.kid|.handlebars|.hbs|.phtml|.jsp|.liquid|.mao|.mhtml|\
.mc|.mi|.myt|.rhtml|.tpl|.ssp|.tea|.twig|.vm|.fhtml|.sls|\
.feature|.tap|.awk|.vim|.pot|.po|.weechatlog|.todotxt|.thy|\
.lean|.rts|.u|.vcl|.bpl|.sil|.vpr|.cirru|.duel|.jbst|.qml|\
.qbs|.slim|.xqy|.xquery|.xq|.xql|.xqm|.whiley|.x10)
# extension recognized
pygmentize -f 256 -O style=$PYGMENTIZE_STYLE "$path"
;;
*)
# parse the shebang script header if it exists
lexer=$(head -n 1 "$path" |grep "^#\!" |awk -F" " \
'match($1, /\/(\w*)$/, a) {if (a[1]!="env") {print a[1]} else {print $2}}')
case "$lexer" in
node|nodejs)
# workaround for lack of Node.js lexer alias
pygmentize -f 256 -O style=$PYGMENTIZE_STYLE \
-l js "$path"
;;
"")
exit 1
;;
*)
pygmentize -f 256 -O style=$PYGMENTIZE_STYLE \
-l $lexer "$path"
;;
esac
;;
esac
;;
esac
done
exit 0
The one drawback about this approach is that Pygments is a Python program, and so on first use during a shell session, there is a "cold start" delay. Subsequent invocations are much faster. – Joe Coder – 2018-10-12T01:52:31.923
Nice! Really comprehensive. – Dario Seidl – 2018-11-11T16:01:29.633
TIL: If you get an error like "awk: line 1: syntax error at or near ," with the above .lessfilter in place, check that gawk is installed. – Bryce – 2019-10-23T23:38:10.023
4
Use the GNU Source-highlight; you can install it with apt
if you have it, or otherwise install it from source. Then set up an "input preprocessor" for less, with help from the Source-highligh' documentations for setting up with less:
This was suggested by Konstantine Serebriany. The script src-hilite-lesspipe.sh will be installed together with source-highlight. You can use the following environment variables:
export LESSOPEN="| /path/to/src-hilite-lesspipe.sh %s"
export LESS=' -R '
This way, when you use less to browse a file, if it is a source file handled by source-highlight, it will be automatically highlighted.
Xavier-Emmanuel Vincent recently provided an alternative version of ANSI color scheme, esc256.style: some terminals can handle 256 colors. Xavier also provided a script which checks how many colors your terminal can handle, and in case, uses the 256 variant. The script is called source-highlight-esc.sh and it will be installed together with the other binaries.
3
Condensed from my full blog post about improving less experience: https://www.topbug.net/blog/2016/09/27/make-gnu-less-more-powerful/
For colorful manpages, add the following to your .bashrc
or .zshrc
:
export LESS_TERMCAP_mb=$'\E[1;31m' # begin bold
export LESS_TERMCAP_md=$'\E[1;36m' # begin blink
export LESS_TERMCAP_me=$'\E[0m' # reset bold/blink
export LESS_TERMCAP_so=$'\E[01;44;33m' # begin reverse video
export LESS_TERMCAP_se=$'\E[0m' # reset reverse video
export LESS_TERMCAP_us=$'\E[1;32m' # begin underline
export LESS_TERMCAP_ue=$'\E[0m' # reset underline
For syntax highlighting, using an existing powerful lesspipe.sh
to handle it instead of writing your own: https://github.com/wofr06/lesspipe
3
To expand upon another answer, you can make it work for most if not all of your scripts that don't have extensions by changing the .lessfilter file around just a bit:
#!/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"
;;
*)
scriptExec=$(head -1 "$1" |grep "^#\!" |awk -F" " '{print $1}')
scriptExecStatus=$?
if [ "$scriptExecStatus" -eq "0" ]; then
lexer=$(echo $scriptExec |awk -F/ '{print $NF}')
pygmentize -f 256 -l $lexer "$1"
else
exit 1
fi
esac
exit 0
You'd still need to add the two variables to .bashrc:
export LESS='-R'
export LESSOPEN='|~/.lessfilter %s'
And you'll still need to make .lessfilter executable:
$ chmod 700 ~/.lessfilter
Also I wanted to add that under debian the pygments package is called python-pygments. I had trouble locating it at first because the obvious misspelling of "pigments" as "pygments" wasn't enough of a hint to me that it was a package that might be prefixed with "python-" by the package manager.
22 comments: 1) Thanks for the improvement. 2) Phrases like "voted best answer" aren't great; that may change (in fact, if this is better than that answer, this post might become the top answer, at which point it'll just be confusing. Maybe just say "to expand upon another answer" or "captaincomic's answer"? – cpast – 2013-02-27T23:07:27.887
2
You can consider using most
utility which is colour-friendly alternative for less
and more
.
can you show us one example? I tried here, and the output was black and white. – danilo – 2019-06-13T17:47:20.443
Your input should contain colours. First produce a colorised sample (e.g. ccze -A </var/log/dpkg.log
, ls -1 --color /var/log
) then pipe it to most
: ls -1 --color /var/log | most
. – Onlyjob – 2019-06-15T00:06:41.443
yes, I used: git status | less --color
, git status | most --color
– danilo – 2019-06-15T00:14:49.970
I used most, more, less, and all tools show black and white – danilo – 2019-06-15T00:17:34.337
Make sure that your command produces colours before piping to less
or others. Make sure your terminal emulator can output colours. Check TERM
environment variable. Read more in https://unix.stackexchange.com/questions/148/colorizing-your-terminal-and-shell-environment
When possible use modern GNU+Linux distribution like Debian. Use search engine (e.g. https://duckduckgo.com/ https://www.startpage.com/) to find answers. Remember that comments are not for discussion.
1
I found this simple elegant solution. You don't have to install anything extra as it is already there by default on most machines. As vim
is installed by default on most machines, it includes a macro to run vim
like less
Some of the options to use it are to create an alias:
alias vless='vim -u /usr/share/vim/vim74/macros/less.vim'
or create a symbolic link:
ln -s /usr/share/vim/vim74/macros/less.sh ~/bin/vless
Then you just run vless myfile.py
I got most of the information here
1I have alias lesser='/usr/share/vim/vim80/macros/less.sh'
in ~/bash_aliases
(in Ubuntu 18.04). Can use shortcuts such as f forward, b backward, d half down, u half up, q quit, etc... – Daniel – 2019-06-05T14:01:43.597
0
The most intuitive and straight forward solution for me was using pygmentize
by adding the lines below to .bashrc
export LESS='-R'
export LESSOPEN='|pygmentize -g %s'
In case you couldn't call pygmentize
, just install like
pip install pygments
ps. The pygmentize
executable binary would sit in /usr/local/bin/
or in your /home/username/.virtualenv/venvname/bin/
or somewhere.
0
An alternative to less/more that works with colors out of the box is bat. You can install it with most package managers use it as a pager as well as a cat replacement.
-2
None of these were working out of the box for me and I figured out an easy way to make this work so I thought I would share.
Just use tmux, that allows you access and scroll through a larger history and preserves the colors perfectly.
1Doesn't tmux permit multiple terminals from one screen, how does it change less's display of colours? – Xen2050 – 2018-10-26T13:23:14.613
@Xen2050 I think it's a neat workaround although this answer doesn't explain how to enter scroll mode (Ctrl-b + [) – siikamiika – 2019-04-18T18:30:23.020
-2
As long as the output text have color control characters, less -R
will do.
This is what another answer (from 9 years ago) says. Answers that duplicate other answers are not useful.
– Kamil Maciorowski – 2019-07-15T12:54:48.133Fair, but that answer doesn't make it explicit that it only works on files that were built with color control characters. – Leonardo Raele – 2019-07-15T13:13:39.233
5
This seems related: http://superuser.com/questions/36022/less-and-grep-color - does it help?
– Jonik – 2010-03-09T13:40:00.1077The title of this question is very misleading. Many people landing on this page expect a solution to the coloring issue you will get when piping a command with colored output to
less
: colors are lost. (The answers to that ”piping issue“ involveless -R
,unbuffer
etc.) But the actual question refers to opening a file! — The ambiguity lies primarily in the question's title, but even besides that, IMHO the question is still too broad: ”read a file“ could refer to any file (probably plain text). (well, ”get the content in colors“ is probably referring to syntax highlighting.) – myrdd – 2018-12-03T23:05:34.447I need to correct myself, only 3 (or 4) of 14 answers are missing the OP's actual question: the answers by ChristopheD, Puneet and Onlyjob; and maybe jbbr. Still, two of those answers are part of the three highest-voted ones.
– myrdd – 2018-12-03T23:38:08.780@myrdd "syntax highlighting" is the relevant term then... (It asks about showing colors, not adding colors?)
less -R
will work on files as well, e.g.ls --color=always > /tmp/file && less -R /tmp/file
– Gert van den Berg – 2019-07-05T10:20:08.963@GertvandenBerg I think the OP meant ”how to get syntax highlighting in
less
ormore
when the file opened does NOT contain any escape codes“. But I only think he meant that, I don't know it. — By the way, I disagree with you interpretation of the question. The question says ”When I read a file […]“, and by ”file“ I'm quite sure the OP meant a typical plaintext file, or a ”normal“ file. Does a ”typical“ plaintext file (or ”normal“ file) contain escape characters, i.e., coloring? No. So IMHO the question is about ”adding“ colors (or syntax highlighting). – myrdd – 2019-07-05T14:30:31.9801@myrdd It might make most sense for the question to be closed as "unclear what is being asked" since questions asking any of the two would likely get marked as duplicates of this... (And answers for any of the two can get downvoted based on how the voter interprets it...) (My use case was a log file that (annoyingly) has color escape codes in it) – Gert van den Berg – 2019-07-07T12:36:20.593
@GertvandenBerg I agree. I already have been voting for closing the question. – myrdd – 2019-07-07T19:21:43.350