Copy a long single-line text from a terminal with undesired change-line

The real behavior of this is the following:

if you are in less and you have a file with a very long line, then if you scroll over the long line down and scroll back up, you have multiple lines, when copying the whole text. After that, when you scroll the splitted lines down over the bottom of the terminal and scroll the lines up again, the line breaks will be removed again.

For visualization:

enter image description here


You can copy the lines of output without extra newlines (line breaks) if the text was output directly to the terminal.
The terminal can keep track of where the real line ends are.

But if the lines were output by less or a similar pager program, the terminal does not know where the newlines are. The pager uses the terminal as a full screen of characters, and tells the terminal "put these characters there" and operations like scrolling. But, for the terminal, there's no way to see where newlines are intended.


Instead of copying what is displayed on the terminal (only what fits on the screen, with), copy the actual text. Use one of the external utilities xsel or xclip (they have mostly the same features, I'll use xsel in this answer) to copy data from or to the X clipboard. To copy to the clipboard, pass the desired content on standard input. When pasting from the clipboard, the content is written to standard output.

In less, use the | command to pipe a bunch of lines through a command. Scroll to the first line you want to act on, type mm to set a mark, scroll to the last line, and type |mxsel -b and press Enter. Two marks are predefined: ^ for the beginning of the file, $ for the end of the file. Thus, to copy the whole file, use <|$xsel -b. To copy a single line, use mm|mxsel -b and Enter.

Remove the -b option to copy to the primary selection instead of the clipboard.