Alby
Alby

Reputation: 5742

How to extract out lines with a pattern and put them in the end of the file

Suppose I have the following text.

a test1
b test2
a test3
b test4

what is the command to use to extract out the lines that start with the letter a and put them in the end of the file like this?

b test2
b test4

a test1
a test3

when I used :g/^a/d and p, the only last match is pasted:

b test2
b test4

a test3

Upvotes: 0

Views: 260

Answers (1)

jamessan
jamessan

Reputation: 42647

You're only seeing a test3 at the end, because :d sets (not appends) the default register. Since :g executes the given command once per line that matches the pattern, only the last line is in the default register when you paste.

The canonical way to do this would be to use the :move (abbreviated as :m) command -- :g/^a/m $. For every line that matches ^a, move it just past the last line ($).

A slight modification to your initial approach would be to have :d append to a register, and then paste that register afterward.

:let @a=''  " Clear register a
:g/^a/d A   " For every line that matches ^a, delete it
            " and append the contents to register a
:$put a     " Paste the contents of register a after the last line

The last part could also be done using the normal mode command "ap.

Upvotes: 5

Related Questions