7

I am trying to do this: deleting lines matching a pattern and then copy these lines into some other place in the file.

:g/PATTERN/d

does delete the lines but when I use p or P, only the last line is inserted to the file from the internal buffer.

How can I do this?

10

You could delete the lines in a register:

First clean up your register q for example with qqq in normal mode.

Then use :g/PATTERN/norm! "Qdd

In normal mode when you use "qdd you replace the content of the q register with the deleted text but if you use "Qdd you append the deleted text to the register.

EDIT As @Matt pointed out in the comments you don't need to use the norm! trick in you global command because :d also accepts a register as a parameter (:h :d) so you can simply use

:g/PATTERN/d Q

You can then use "qp to past the content of the register where your want to.


Another solution is to combine :h :move with the global command. For example to move all the matching lines at the end of the buffer:

:g/PATTERN/move $
2
  • 3
    d Q is enough. No need for "normal".
    – Matt
    Feb 18 at 11:22
  • Thank @Matt I completely forgot about this syntax for :d and didn't take the time to look at the doc! I'll edit my answer.
    – statox
    Feb 18 at 11:25
3

The reason why you get only the last line back is that :g works on the found lines line by line. This means that every next delete operation overwrites the previous content of the register used.

To overcome this you must use a named register (A-Z) and use the uppercase name, which causes the new content not overwriting the previous one but appending to the register.

g/PATTERN/d A

will append all deleted lines to the register a.

Now that register will not be empty, so you must clear its contents before using it.

qaq will start to record a macro into register a and immediately stop again, thus clearing its contents.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.