Copy specific line from less

2019-04-07 12:22发布

问题:

In the end after searching google I decided to write on stackoverflow, I couldn't find any solution about my simple problem, therefore I am even more surprised.

The question is:

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.

回答1:

tl;dr, use m and |

Example:

  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.

Within the man page of less, 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.

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

Note

Actually 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 a backward way, namely from bottom to top, otherwise, less might behave awkwardly, and throw the whole screen through the pipe.



回答2:

I think I found the solution: it is using tmux. Tmux provides it's own clipboard ( correct me if I am wrong ). From tmux I can enter the copy-mode wherever I am ( in MAN pages, less, console output ) and let me to copy the content.



回答3:

Short answer: Ctrl+C and Ctrl+V are associated with other actions. For instance Ctrl+C sends an interrupt signal to the foreground process. Usually you need to use Ctrl+Shift+C and Ctrl+Shift+V in order to copy and paste from a terminal.

Long answer: This very good thread from superuser.