Learn Practice Daily golf Reference

How to delete all lines in Vim

In Normal mode, press gg to go to the first line, then dG to delete to the last. Or type :%d and press ↵, which works from any line.

Try it here

Clean up a log, then clear it

First take out the noise: :g/DEBUG/d and ↵ deletes every line that mentions DEBUG. Then empty the file with ggdG.

1 of 2Delete every DEBUG line with :g/DEBUG/d
1INFO server started on :8080
1DEBUG cache warmed in 120ms
2ERROR disk quota exceeded
3DEBUG retrying upload (1/3)
4INFO upload finished
5INFO shutting down
NORMALLoading the editor…1/20.0s1:1

This editor needs a keyboard. Read on, and play it at your computer.

KeysDeletes
ggdGevery line: go to the top, then delete to the bottom
:%d ↵every line, wherever the cursor is (% means the whole file)
:1,$d ↵the same, spelled out: line 1 to the last line ($)
dGfrom the cursor line to the end of the file
dggfrom the cursor line to the top of the file
:%d _ ↵ or gg"_dGevery line, without replacing what you copied (see below)
:g/pattern/d ↵every line that matches pattern
:v/pattern/d ↵every line that does not match pattern (:g! is the same)

Why ggdG works

d is the delete operator and G is a motion to the last line. Together, dG deletes every line from the cursor down, so starting from the top with gg takes the lot. Vim leaves one empty line behind: a file always has at least one line, even when it has no text.

:%d does the same from the command line. The % is a range meaning every line, so it doesn't matter where the cursor is. Any range works: :1,$d is the long way to write it, and :10,$d deletes from line 10 to the end.

Before
INFO server started on :8080
DEBUG cache warmed in 120ms
ERROR disk quota exceeded
DEBUG retrying upload (1/3)
INFO upload finished
INFO shutting down
:v/ERROR/d↵
ERROR disk quota exceeded
:v/ERROR/d deletes every line that does not mention ERROR, leaving only the errors

All the lines that match, or all that don't

:g/pattern/d runs :d on every line that matches the pattern, so :g/console\.log/d strips every logging line from a file. :v/pattern/d (or :g!/pattern/d) does the opposite and keeps only the matching lines, which is a quick way to boil a long log down to its errors. Both are one change, so a single u undoes them.