PlainOldProgrammer
PlainOldProgrammer

Reputation: 2953

Get only the lines that appear only once and delete all lines that have 2 or more occurrences in Vim

Suppose I have a text file with:

Bar
Foo
Bar
Foo
Baz
Bar

And I want only the unique lines that doesn't have more than 1 occurence:

Baz

I use :sort ui but it returns:

Bar
Baz
Foo

How can I get the lines that doesn't have any repetition?

Upvotes: 2

Views: 95

Answers (2)

Conspicuous Compiler
Conspicuous Compiler

Reputation: 6469

You need to first sort the lines, then replace any line followed by that line duplicated any number of times with an empty string:

e.g.

:sort i
:%s/^\(.\{-1,\}$\)\n\?\(\1$\n\?\)\+//gi

Upvotes: 2

Peter Rincker
Peter Rincker

Reputation: 45147

Time for some awk:

:%!awk '{a[$0]++} END{ for(k in a){ if(a[k] == 1) { print k }} }'

The idea is simple: Read each line into a hash table as the key and increment the value. This means the value will store the number of times a line has been seen. After you are done reading the file then loop through the hash table and print out each key that is seen only once.

Upvotes: 3

Related Questions