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 :g/pattern/d deletes all matching lines, :v the others

Vim
~/tips/tip-vim-global-d-delete-matching-lines

:g/^#/d

Deletes all lines containing a pattern, or all lines not containing it, in one command.

Cleaning a log or a config file by hand, line by line, is the kind of job Vim’s global command was made for.

:g/^#/d
:v/error/d
:g/^$/d

The syntax is :[range]g/{pattern}/[cmd]. It runs the Ex command on every line in the range where the pattern matches. The range defaults to the whole buffer and the default command is :print. So the first line above deletes every line that starts with #, and the last one removes the empty lines.

:v is the inverse, the same as :g!. It runs the command on lines that do not match, so :v/error/d keeps only the lines with the word error.

The manual points out that undo reverts the whole global command at once. One u brings everything back.

It also mentions a variant for large jobs: :g/pattern/d _ sends the deleted lines to the black hole register, so your registers and clipboard are left alone, and the command runs faster.

The caveat is that the pattern is a Vim regular expression, which is not the same as grep’s. Run :g/pattern/ without the d first. It prints the matching lines, so you see what you are about to delete. Do that before the real thing, especially with :v, where a typo deletes nearly everything.

Further reading: Vim help: repeat.txt, :global

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