2

I have a file containing a list of words, e.g. list.txt contains:

carrot
apple
pen
ukulele
pen
cinnamon
carrot
carrot

How do I sort this file so that the words which appear the most in it go to the top, and duplicates are removed?

e.g. I'd like list.txt to contain this after sorting:

carrot
pen
apple
cinnamon
ukulele

1 Answer 1

3

Normaly, I would use

:%! sort | uniq -c | sort -nr

but this is a shell depended answer.

Using only Vim language or ex-commands in Vim is a little bit more difficult and it is very nicely described on wikia in Word frequency statistics for a file.

Inspired by that article it is possible to replicate the output of :%! sort | uniq -c | sort -nr with

:%s/^\+/1\t/g
:sort
:g/^\c\(.\+\)\n\1$/norm! ^yiwj@"^Akdd
:sort! n

The ^A represents Ctrl-A and is inserted as CTRL-V + CTRL-A (or if you use Ctrl-V for paste, press Ctrl-Q then Ctrl-A).

2
  • your solution seems to be prepending numbers, I don't want these.
    – user9024
    Commented Oct 30, 2016 at 21:24
  • 1
    So just delete them :-) You can use any way you want. Exampli gratia, :%s/\d\t// .
    – ryuichiro
    Commented Oct 30, 2016 at 21:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.