46

Is it possible to pipe output (e.g. dmesg) to a command like less (or equivalent) and keep the text highlighting used by the original command?

example: on the left dmesg | less on the right dmesg

<code>dmesg | less</code> vs <code>dmesg</code>

Steven
  • 27,531
  • 11
  • 97
  • 118
apoc
  • 673
  • 2
  • 6
  • 12

3 Answers3

53

Use the --human parameter to view colored dmesg output in a less-like environment.

dmesg --human --color=always

Or use the short version:

dmesg -H

Alternatively, use the following command to achieve similar results.

dmesg --color=always | less -R

Many other utilities that produce colored output (ls, grep, etc.) have a similar --color=always option.

Steven
  • 27,531
  • 11
  • 97
  • 118
  • 2
    Actually `--human` does more than just preserve color and pipe to `less`: it also marks dates as e.g. `[May23 00:58]` and subsequent small offsets as `[ +6.046768]` instead of what would always be `[121187.191521]` with `less`. – Ruslan May 23 '17 at 12:56
  • Is there a way to make this preserving of color formatting automatic for anytime I'm piping *any* txt based command (not just dmesg)? – mikemtnbikes Aug 02 '18 at 18:48
  • @mikemtnbikes You have to use the `--color=always` if provided by the program. A program knows if it is outputting to a pipe and can therefore decide to output color or not. – Steven Aug 22 '18 at 16:04
  • 1
    `git` also has the `--color=always` option – Axel Bregnsbo Aug 23 '20 at 15:25
  • `dmesg -H -T` gives absolute timestamps, e.g. `[Sat Jul 3 02:39:08 2021]` instead of `[ +0.000002]` – Bob Stein Jul 04 '21 at 19:36
1

A generic command to preserve coloration independent of the program providing the output is the unbuffer command (which is part of the expect package).

Usage:

unbuffer dmesg | less -R
Artur Meinild
  • 152
  • 1
  • 14
0

Yes, it works nice.

  • for tree: tree -C | less -r

  • for ls: ls -lA --color=always | less -r

  • for pytest: py.test --color=yes | less -r

Peregrino69
  • 4,526
  • 2
  • 22
  • 30