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

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

    At moment I do that using something like this to remove all lines in a file:

    echo > test.txt

    How can I delete all lines using vi?

    Note: Using dd is not a good option. There can be many lines.

    I think dG should work.

    @MadTux, only if you start on the first line. `1GdG` would work from anywhere.

    `echo | test.txt` is not a valid command, unless `test.txt` is an executable script. I'm guessing you mean `echo >test.txt` instead?

    You are right @tripleee

    Note that *not* using `vi`, `>test.txt` is sufficient to truncate it to zero length - no `echo` needed.

    On the command line prefer `rm test.txt;touch test.txt` The echo creates a file with 1 character (new line) in it. While touch creates an empty file.

    Depending upon the circumstances, you might be better off using `logrotate(8)` instead. Why do you want to delete all lines in the file?

    ``ggVG`` puts the whole file into a visual block. A simple `d` afterwards deletes the block. Using ``j``, ``k`` etc. one can adapt the visual block. Using ``o``, the cursor jumps to the block's other end.

  • Anthon

    Anthon Correct answer

    6 years ago

    In vi do


    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.

    Pro tip. No more `ESC+dd+dd+dd+dd+dd+dd+dd+dd+dd+dd+dd+dd+dd+dd+dd+dd...`

    @rdev5 try `.` next time to repeat a command

    Even with `:%d` and enter, its way too many strokes. I am trying to get into vim but without vim ctrl + a and del button is much more simpler than what vim provides for this. Just two strokes(ctrl+a, del) unlike `:%d` which has 4 strokes including the enter command

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM