Łukasz
Łukasz

Reputation: 463

How do I yank the text matching a pattern?

I am trying to perform an action on a searched pattern but I can't figure out how to do that. The goal here is to be able to yank a pattern but so far I can only yank a whole line. Is there a trick that will make this command operate only on a matched pattern?

:/pattern.*/v

Upvotes: 6

Views: 1923

Answers (2)

1983
1983

Reputation: 5963

To yank all text matched by a pattern, define a function to store a string in a register:

fun! Save(s)
    let @a .= a:s . "\n"
endfun

Then, clear your register and perform the following substitution:

:let @a='' | %s/mypattern/\=Save(submatch(0))/g

This will evaluate the expression Save(submatch(0)) each time the pattern matches (see :help :s\=), and use that for the substitution. submatch(0) returns the matched text (same as &), and Save will append this to register a. Don't forget to undo afterwards, or include return a:s in the function if you don't want to make destructive edits.

You can then :new | put a to see the results. If you want other information, such as line numbers where the matches occurred, amend the function:

fun! Save(s)
    let @a .= line('.') . ': ' . a:s . "\n"
endfun

Upvotes: 0

romainl
romainl

Reputation: 196876

If your Vim is recent enough (7.3.6xx), you can use gn in combination with :normal:

:/foo/normal ygn

To yank to a specific register:

:/foo/normal "aygn

See :help :normal and :help gn.

Upvotes: 8

Related Questions