How to Copy All Lines Matching a Search Pattern
The aim of this pageđź“ť is to explain yanking multiple matches in Vim based on the particular example of yanking lines containing a pattern. The benefit is that it is relatively quick. The downside is that moving it out of vim seems painful.
2 min readAug 27, 2024
- Vim allows yanking lines containing a pattern using the
:g
command. - The command
:g/pattern/y
yanks lines matching the pattern. - By default, this command stores only the last match in the unnamed register. As multiple matches keep overwriting the register.
- Using a lowercase register (e.g.,
a
) also stores only the last match for the very same reason. - To collect all matches, use an uppercase register (e.g.,
A
). - Uppercase registers append new content to existing content.
- Use
qaq
to clear ana
register. This is important as you don’t want to append the matches to the existing content of thea
register! - Example to yank lines into a register after
qaq
is
/<searchPattern>
:g##y A
- But you have it in a named register so further work needs to be done to bring it out of Vim — if you use Vim as a data-wrangler/thought-builder, as I do.
LINKS
- https://vimhelp.org
- https://vim.fandom.com/wiki/Yank
- https://vim.fandom.com/wiki/Power_of_g
- http://vimcasts.org/episodes/using-vims-named-registers/
ANKI
Q: What does the `:g/pattern/y` command do in Vim?
A: It yanks lines matching the pattern into the unnamed register, but only stores the last match.
Q: How do you clear a register in Vim?
A: Use the command `:let @a=''` to clear register `a`.Q: What is the difference between using a lowercase and an uppercase register in Vim?
A: Lowercase registers overwrite existing content, while uppercase registers append new content.Q: How can you collect all matches of a pattern into a register in Vim?
A: Use the command `:g/pattern/y A` to append all matches to register `A`.Q: How do you copy content from a named register to the unnamed register in Vim?
A: Use the command `:let @"=@A` to copy content from register `A` to the unnamed register.Q: What is the purpose of using an uppercase register in Vim?
A: To append new content to the existing content in the register.Q: What happens when you use `:g/pattern/y a` in Vim?
A: It yanks lines matching the pattern into register `a`, but only stores the last match.Q: How do you ensure all matches are collected in Vim?
A: Use an uppercase register to append all matches.Q: Why might you want to clear a register before yanking lines in Vim?
A: To avoid appending new content to existing content in the register.