How to Yank/Copy all Lines Matching a Pattern
The aim of this page📝 is to share steps for copying all lines with a particular match using the global
command.
2 min readSep 12, 2024
As part of my job in ops, I often have a larger set (hundreds) of commands, when I need to execute just a subset of them. I define a pattern until I’m happy → run <leader> y
in vim and have that subset in a system clipboard ready for action. How do I get to that <leader>y
command?
full steps — this is what you do manually
- delete register ‘a’ with
qaq
- find match with
/<pattern>
(you could do this in step-3, but you may want to iterate until you get a right match so it's always a separate step for me) - combine
global
+pattern
+yank
withg##y A
— the capitalA
is essential as this is what keeps appending to a registera
and not overwriting it with every single match. You would end up with only the last matched line if you useda
instead ofA
- annoyingly, to extract register
a
into system clipboard you have to run:let @+ = @a
simplified steps — this is how you get to <leader>y
- Put the following into
.vimrc
- the y in
<leader>y
can be replaced with any letter, I use that for semantic proximity (y is for yank, which is copy in vim’s weird lingo, etc).
nnoremap <leader>y :call MyCustomYank()<CR>
function! MyCustomYank()
" Clear register 'a'
execute 'normal! qaq'
" Append lines matching the pattern to register 'A'
execute 'g##y A'
" Move the contents of register 'a' to the system clipboard
let @+ = @a
endfunction
- Search for pattern with
/<pattern>
- Copy to system clipboard with
<leader> y
LINKS
https://vimhelp.org/repeat.txt.html#:global https://vim.fandom.com/wiki/Power_of_g#Examples