Nelson Teixeira
Nelson Teixeira

Reputation: 6610

How do I remove non-duplicate lines in Vim?

How do I remove all non-duplicate lines in Vim ? There are plenty of solutions for removing duplicates lines. I wanna do it backwards. I want to leave only those lines that have at least a duplicate.

Does anyone know how?

Upvotes: 3

Views: 1825

Answers (3)

Ingo Karkat
Ingo Karkat

Reputation: 172778

My PatternsOnText plugin now has a :DeleteUniqueLinesIgnoring command that does this.

Upvotes: 2

romainl
romainl

Reputation: 196926

:%y               yank the whole buffer
:vnew             create a new vertical window
Vp                paste in place of line 1
:sort             sort the buffer
:%!uniq -u        remove duplicates
:%s/.*/g\/&\/d    turn every line into a :global command that deletes the matching line
:%y               yank the whole buffer
:bw!              delete that buffer 
                  (and close the window and move back to the original window)
:@"               execute the :global commands contained in the unnamed register

Which, admittedly, is a lot more typing than Kent's answer but, hopefully, demonstrates Vim's versatility.

Upvotes: 2

Kent
Kent

Reputation: 195289

if you were on Linux box, give this line in vim a try:

:%!awk 'a[$0]++'

If you are looking for pure vim/vimscript solution, you could build a dictionary in vim, key is the line text, value is how many times the line occurred in buffer, finally filter out those value ==1 entries.

read doc for :h dict :h filter(

Upvotes: 7

Related Questions