vimcopy-pasteex

Vim ex mode: copy pattern and paste at the end of file


I'm trying to automate some simple modifications to a set of files with a script using Vim ex mode. What I want to do is search for a pattern, delete it from its current location (just the pattern, not the whole line), and paste it at the end of the document.

There are some useful suggestions at the following URL, but I feel like there ought to be a way of doing this without defining a special function. Copy search matches

Recommendations?


Solution

  • Ex commands typically work on entire lines. However we can use the command :s to "capture" all the matches into a register and then paste them at the end of the document.

    :let @a=""
    :%s//\=matchstr(setreg('A',submatch(0),'l'),'')/g
    :$put a
    

    Explanation:

    For more help see:

    :h :let
    :h :s
    :h range
    :h :s\=
    :h submatch(
    :h setreg(
    :h matchstr(
    :h :pu
    :h registers