How do I yank all matching lines into one buffer?

Vim

Vim Problem Overview


How do you yank all matching lines into a buffer?

Given a file like:

match 1
skip
skip
match 2
match 3
skip

I want to be able issue a command to yank all lines that match a pattern (/^match/ for this example) into a single buffer so that I can put it into another doc, or into a summary or whatever.

The command should wind up with this in a buffer:

match 1
match 2
match 3

My first thought was to try:

:g/^match/y

But I just get the last match. This makes sense, because the :g command is effectively repeating the y for each matching line.

Perhaps there is a way to append a yank to buffer, rather than overwriting it. I couldn't find it.

Vim Solutions


Solution 1 - Vim

:g/^match/yank A

This runs the global command to yank any line that matches ^match and put it in register a. Because a is uppercase, instead of just setting the register to the value, it will append to it. Since the global command run the command against all matching lines, as a result you will get all lines appended to each other.

What this means is that you probably want to reset the register to an empty string before starting: :let @a="" or qaq (i.e., recording an empty macro).

And naturally, you can use the same with any named register.


Solution 2 - Vim

:help registers
:help quote_alpha

Specify a capital letter as the register name in order to append to it, like :yank A.

Solution 3 - Vim

Oh I just realized after commenting above that it's easy to yank matching lines into a temporary buffer...

:r !grep "pattern" file.txt

The simplest solutions come once you've given up on finding them. :)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondaotoadView Question on Stackoverflow
Solution 1 - VimrampionView Answer on Stackoverflow
Solution 2 - VimJosh LeeView Answer on Stackoverflow
Solution 3 - Vimdash-tom-bangView Answer on Stackoverflow