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.

Pavol Kutaj
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

  1. delete register ‘a’ with qaq
  2. 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)
  3. combine global + pattern + yank with g##y A — the capital A is essential as this is what keeps appending to a register a and not overwriting it with every single match. You would end up with only the last matched line if you used a instead of A
  4. 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

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com