Easy way - grep
The easiest technique is to use :%!grep -o {pat}
. The -o
/--only-matching
make grep only display the matches.
:%!grep -o 'foo\w*bar'
Note: that grep's regex's are a different variant from PCRE and Vim's.
Pure Vim method with plugin - still easy
For a pure native vim solution I suggest you look at ExtractMatches or Yankitute plugins.
(Ab)Using :s
for fun and profit
You want to roll your "extract matches" command with :s
with a sub-replace-expression (\=
) and a list.
let lst = []
:%s/pattern/\=add(lst, submatch(0))[-1]/g
:%d
:pu=lst
:1d
The basic idea is to add each match to the list, lst
, using a sub-replace-expression for the :s
command. We can use some in-place array trickery to make sure the text doesn't change by always returning the last element of the array (what we just added).
This :s
trick is often done in the form:
:let lst = []
:%s//\=add(lst, submatch(0))[-1]/g
:call setreg('"', join(lst, "\n"), 'l')
This will capture the current matches (uses last used pattern) into the default register. If you have Vim 7.4 then the :s
can be simplified further: :%s//\=add(lst, submatch(0))/gn
More information
:h :range!
:h :s
:h sub-replace-expression
:h List
:h add()
:h submatch()
:h :d
:h :pu
:h @=