BreezePaul
BreezePaul

Reputation: 43

How to count the duplicate times of duplicate lines in Vim?

Now I am working on Windows with Gvim. I want a pure Vim way without using the external command of the operating system, to count the duplicate times of duplicate lines in Vim. In other words, I want a pure Vim way working like ":!sort % | uniq -c".

Upvotes: 2

Views: 1250

Answers (2)

Armali
Armali

Reputation: 19395

While romainl's implementation is perfectly correct, using a dictionary to count the occurrences may have a better time complexity.

:let dict={}
:g/$/let ln=getline(".") | if !has_key(dict, ln) | let dict[ln]=0 | endif | let dict[ln]+=1
:for [k, v] in items(dict) | echo v." ".k | endfor

Upvotes: 5

romainl
romainl

Reputation: 196751

There is no ready-made equivalent. Below is a quick and dirty approximation.

Doing:

:echo getline(1,'$')->map({ idx, val -> getline(1,'$')->count(val) .. ' ' .. val })->sort()->uniq()->join("\n")

on this buffer:

foo
foo
bar
baz

echoes this:

1 bar
1 baz
2 foo

in the command-line, which should provide a good starting point.

Breakdown:

:echo {expr}

echoes the output of {expr} in the command-line.

getline(1,'$')

returns a list with every line in the buffer.

->map({ idx, val -> getline(1,'$')->count(val) .. ' ' .. val })

prepends each item of the list with its count in the list.

->sort()

sorts the list.

->uniq()

removes duplicate items from the list.

->join("\n")

and finally joins it with newline as separator so that it looks good when echoed to the command-line.

Upvotes: 6

Related Questions