Run commands of the own over a opened file in less. Is it possible

less

I was wondering if it would be possible to run commands of my own over the less command. With this I mean being able to have a file open in less and then run some command of mine over what I'm seeing (or even the whole file, if needed be) while keeping the screen as it is. For instance, I would like to be able to run different scripts that would color what I'm currently seeing in different ways, or to show / hide certain lines in the file.

I know I can every time make a different run of cat <file> | my-script | less -R but that doesn't give me the editor-like experience that less provides.

Best Answer

You can use the | command in less to pipe the file through a different program.

  1. Press |.
  2. Enter a mark letter or ^ or $ or ..
  3. Type the shell command to execute.
  4. Press Enter.

Only the part of the file between the current position and the mark is piped. The mark can be either ^ or $ meaning the beginning and end of the file respectively, or a position defined with the m command. The current position is the line at the of the screen if the mark is before that, and the line at the bottom of the screen otherwise. In particular, to pipe the whole file, either use <|$mycommand or >|^mycommand to set the position to one end of the file and the mark to the other end. To pipe just the lines that are shown on the screen, use the mark ..

The output of the command won't stay on the screen; If you want to browse the output with less you'll need to start another instance, e.g. rot13 | less. When you quit that second instance of less, you'll be brought back to the first. There's no way to replace the content of the current instance by data piped from it. To see colors, remember to run less -R.

Related Question