0

For the below data:

-150000    2023-03-30
421.67     2023-04-20
575        2023-05-20

I can substitute the whole line with the first string

:%s/\v.{-1,}\s+(.+)/\1

Then the content was changed into:

-150000
421.67
575

I can copy the lines into register + with:

:%y+

With my method the primitive data was

-150000    2023-03-30
421.67     2023-04-20
575        2023-05-20

converted into

-150000
421.67
575

,then copy it and create a recovery with undo.

How can copy the matched string into register + without changing the previous lines ?

3
  • I'm confused :-/ In your example, what do you want to be copied into the + buffer? All the dates? All the lines with more than one words? The first words of line with more than one word? Mar 31 at 5:19
  • Remark: I suspect that the first parenthesis in the regular expression is mistyped. Mar 31 at 5:21
  • Your current method seems fine to me.
    – romainl
    Mar 31 at 6:17

2 Answers 2

3

Let's first clear the + register, because we want to append to the clipboard (+) register:

let @+=''

Now we will use the setreg() function to append to the + register. Since we only want to work with the matched string, and don't want to actually do some substitution, you can use the n flag of the :s command.

%s/\v.{-1,}\s+(.+)/\=setreg('+',submatch(1),'aV')/ng

This runs your :s command, retrieves the submatch(1) from your pattern and operates on the match, while not substituting anything. This internally runs in the sandbox, so not all functions may be safe. But appending to a register should generally be safe.

2
  • Makt it more simple and clear %s/\v.{-}\s+(.+)/\=setreg('+',submatch(1),'al')/ng
    – showkey
    Mar 31 at 8:38
  • I don't see what is there more simple and clear Mar 31 at 12:13
1

Here is one way to achieve your goal:

qaq
:g/^/call setreg('A', expand('<cWORD>'), 'V')
  • qaq starts a recording into register a and then immediately stops it, which is a handy way to empty register a. See :help recording.
  • :[range]g/<pattern>/<command> executes <command> on every line in [range] that matches <pattern>. See :help :g.
  • the <pattern>, ^, is a trick to match "every line",
  • the <command>, call setreg('A', expand('<cWORD>'), 'V'), essentially tells Vim to append the current WORD to register a in linewise mode. See :help setreg() and :help WORD.

For register +:

:let @+=''
:g/^/call setreg('+', expand('<cWORD>'), 'Va')
2
  • q+q does not work for register + Mar 31 at 9:57
  • Ho crap. Then it's really :let @+=''.
    – romainl
    Mar 31 at 10:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.