brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Vim's :sort orders lines, and can sort by number or drop duplicates

Vim
~/tips/tip-vim-sort-lines-numeric-unique

:sort

Sorts the lines of a file or a selection, with options for numbers, case and duplicates.

Sorting a list in Vim without leaving the editor saves a trip to the shell and back. :sort is built in.

:sort
:sort!
:sort i
:sort n
:sort u

With no range it sorts the whole buffer. Select lines in visual mode and type :sort to sort only those. The options come from the manual: ! reverses the order, i ignores case, n sorts on the first decimal number in each line, and u keeps only the first of a run of identical lines. You can combine them, so :sort nu works.

A pattern changes what is compared. The manual’s example :sort /[^,]*,/ skips the first comma-separated field and sorts on the second. Add r after the pattern to sort on the match itself instead of skipping it.

Other number kinds exist: f for floats, x for hexadecimal, o for octal and b for binary. Those five are mutually exclusive.

The caveat is that the default is a plain comparison, so 10 sorts before 9. Use n when the lines start with numbers. And u only keeps the first of a run of identical lines, so duplicates that are not next to each other survive unless you sort in the same command. If the result is wrong, press u in normal mode to undo.

Further reading: Vim help: change.txt, sorting text

Going deeper: Guide: advanced tmux, a config that grows with you, formats, layouts and more

More Vim tips :%s/<Ctrl-r><Ctrl-w>/newname/g /oldname find . -name "*.conf" | vim – vim --clean file.txt :set textwidth=72 All Vim tips (45) All topics

Link