Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy specific line from less

How to copy a specific line from less ? Lets say I am opening a man ( which is by default opened by less ) and want to select and copy it to clipboard and after that lets say paste it to file opened in vim ? I don't want to use the mouse wheel to paste. I am looking for a simple Ctrl-c , Ctrl-v method as in windows.

When opening a man page I can't switch to my default editor (which is vim ) with 'v' key because less shouts with "Cannot edit standard input" error. Thanks a lot and sorry if this question is silly.

like image 959
friko Avatar asked Oct 29 '14 09:10

friko


People also ask

How do I go to a specific line number in less?

All you have to do is pass either -N or --LINE-NUMBERS option to the less command.

How do you copy multiple lines in less?

Use the | (pipe) command in less to send the text to xclip . Details: Using whatever less commands you like, scroll up or down to position the last line you want to copy at the top of the screen. You can skip this step and the next step if you want to copy all the way to the end.


1 Answers

tl;dr, use m and |.

Example:

Within the man page of less, by running man less:

  1. 7g
  2. mx
  3. 6g
  4. |x
    • xclip (Linux) or pbcopy (macOS), to copy to clipboard.
    • cat > file, to save to file, or cat >> file for append mode.

We would get:

   less - opposite of more    
    

The key things to learn are just two less commands: m (mark), and | (pipe).

Command m (mark)

Followed by any lowercase letter, marks the current position with that letter.

The marker we used above is x, as in step 2, it marked line 7 with x.

Command | (pipe)

| <m> shell-command

<m> represents any mark letter. Pipes a section of the input file to the given shell command.
The section of the file to be piped is between the first line on the current screen and the position marked by the letter.
<m> may also be ^ or $ to indicate beginning or end of file respectively. If <m> is . or <newline>, the current screen is piped.

Using |xpbcopy, we pipe the line-range [7, 6] into pbcopy, as line 6 is currently the first line on the screen, and line 7 is the one we marked as x, and pbcopy is the command to put text into the macOS clipboard.

Alternatively, use xclip on Linux, or even dd of=/path/to/file to save as a file.

Note

The text range is boundary inclusive, so both the beginning and the ending lines of the range, or at least 2 lines are copied.

We marked the range in the backward way, namely from bottom to top, otherwise, less might behave awkwardly, and throw the whole screen through the pipe.

like image 175
ryenus Avatar answered Oct 04 '22 04:10

ryenus