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.
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.
This editor needs a keyboard. Read on, and play it at your computer.
| Keys | Deletes |
|---|---|
| ggdG | every 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 ($) |
| dG | from the cursor line to the end of the file |
| dgg | from the cursor line to the top of the file |
:%d _ ↵ or gg"_dG | every 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.
INFO server started on :8080DEBUG cache warmed in 120msERROR disk quota exceededDEBUG retrying upload (1/3)INFO upload finishedINFO shutting downERROR disk quota exceededAll 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.