275

I have very large files (more than 10Gb). I need only some lines from the top of the file. Is it possible (in vim) to delete the rest of the file (from current line to the end of file)?

1
  • 16
    I know you want to use Vim, but I'd do a shell command like: head -n <number_of_lines> <filename> > <truncated_filename> Where -n is the parameter for the number of lines you want from the top
    – EhevuTov
    Commented Oct 28, 2014 at 23:04

5 Answers 5

455

dG will delete from the current line to the end of file

dCtrl+End will delete from the cursor to the end of the file

But if this file is as large as you say, you may be better off reading the first few lines with head rather than editing and saving the file.

head hugefile > firstlines

(If you are on Windows you can use the Win32 port of head)

5
  • 20
    you can specify how many lines head supplies with eg: head -n20 hugefile for the first 20 lines. n defaults to 10.
    – drevicko
    Commented Oct 30, 2012 at 0:38
  • 4
    Need a motivation for head? Using dG on a large file (1G+) takes a lot of time (e.g., 5 minutes).
    – BurninLeo
    Commented Sep 23, 2015 at 13:28
  • 5
    For those looking for the converse, dgg will delete from the current line to the start of the file.
    – stevesliva
    Commented Apr 12, 2017 at 21:00
  • d Ctrl+End did not work for me. d Shift+End did though to delete from the cursor to the end of the line.
    – lightwing
    Commented May 4, 2018 at 16:30
  • Thx! BTW, there is a keyboard substitute for <END> keystroke? Commented Sep 14, 2023 at 9:10
94

Go to the first line from which you would like to delete, and press the keys dG

1
  • 47
    don't press ":" before you type dG Commented Nov 14, 2011 at 16:13
45

:.,$d

This will delete all content from current line to end of the file. This is very useful when you're dealing with test vector generation or stripping.

1
  • 3
    I prefer to have more control of the starting line, so I use: :<line number>,$d for example: :3,$d will delete from line 3 to the end of file
    – emont01
    Commented Nov 28, 2017 at 14:29
6

I use the following steps to do the same-

  1. Make sure you are in the normal mode by pressing Esc .
  2. Enter the Visual mode by pressing V .
  3. Press G i.e Shift + g to select the text from the cursor to the end of the file .
  4. Now press x to delete the selected text .
1

Just add another way , in normal mode , type ctrl+v then G, select the rest, then D, I don't think it is effective , you should do like @Ed Guiness, head -n 20 > filename in linux.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.