How can I delete all lines in a file using vi?

In vi do

:1,$d

to delete all lines.

The : introduces a command (and moves the cursor to the bottom).
The 1,$ is an indication of which lines the following command (d) should work on. In this case the range from line one to the last line (indicated by $, so you don't need to know the number of lines in the document).
The final d stands for delete the indicated lines.

There is a shorter form (:%d) but I find myself never using it. The :1,$d can be more easily "adapted" to e.g. :4,$-2d leaving only the first 3 and last 2 lines, deleting the rest.


In vi I use

:%d

where

  • : tells vi to go in command mode
  • % means all the lines
  • d : delete

On the command line,

> test.txt

will do also.

What is the problem with dd?

dd if=/dev/null of=test.txt

where

  • /dev/null is a special 0 byte file
  • if is the input file
  • of is the ouput file

I'd recommend that you just do this (should work in any POSIX-compliant shell):

> test.txt

If you really want to do it with vi, you can do:

  • 1G (go to first line)
  • dG (delete to last line)

Tags:

Vi