Saving piped output with less


The problem

You’ve piped the lengthy output of some command to your pager, less. As you’re scrolling through the output you realize you’d like to save it to disk. The output took a long time to generate, so you don’t want to re-run the original command just to redirect the output to a file.

Your first instinct might be to press ‘v’ to edit the output with $EDITOR. less will balk “Cannot edit standard input (press RETURN)”.

The solution

The solution is to use less’ “|” command key to pipe the output to tee which will write it to a file. See the “Commands” section in LESS(1) for the full syntax of this command. Pressing the ‘h’ command key for “help” will give an abbreviated syntax under its “MISCELLANEOUS COMMANDS” section:

"|Xcommand   Pipe file between current pos & mark X to shell command."

You want to pipe the entire buffer to a file so first press “g” to go to the first line. Next, press the “|” key followed by “$” to indicate you want to pipe right up until the end of the buffer. “$” is a predefined mark for the end of the file. Lastly, type “tee” followed by a space and the name of the file you’d like to save to.

So, from anywhere in a less buffer, you can type the following to save the buffer to a file named foo.txt:

g|$tee foo.txt

you’ll see “|done (press RETURN)”.

Further reading

  • LESS(1) –log-file
  • git-diff-tree(1) –pickaxe-regex

Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

Be the first to leave a comment!