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 :%! runs the whole file through a shell command

Vim
~/tips/tip-vim-filter-range

:%!sort -u

Replaces lines in the buffer with the output of a command.

Unix already has good tools for sorting, formatting and cleaning text. Vim can send part of a file through one of them and put the result back.

:%!sort -u

% means every line. Vim passes those lines to sort -u on standard input and replaces them with what the command prints. So the file is sorted with duplicates removed, and u undoes it if you don’t like it.

It works on any range. Select a few lines in visual mode, press :, and Vim fills in '<,'> for you:

:'<,'>!column -t

That lines up a messy block of columns, which I find hard to do by hand. Other favourites: :%!jq . to pretty print JSON, and :%!python3 -m json.tool where jq isn’t installed.

This is different from :r !cmd, which inserts output and keeps your lines. Here your lines are replaced.

If the command fails, its error message replaces your text too. With :%!jq . on broken JSON, the buffer suddenly contains a jq parse error. Press u right away and your file is back.

Further reading: Vim help: :range! filter

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