Flash Sale:75% Off Hosting + Free DomainEnds in13h47m14sView Plans
Hostvento logoHostvento

Delete Lines in Vim and Vi

One line, many lines, a range or all lines that match a word. Here are the commands.

VPS and Cloud Servers2 min read14 screenshots

Install Vim

On Debian and Ubuntu:

sudo apt install vim -y
Installing Vim

On Red Hat based systems:

sudo yum install vim -y

or:

sudo dnf install vim -y

Check the installation:

vi --version
The Vi and Vim version

Delete one line

Press Esc to make sure you are in normal mode. Move the cursor to the line and type:

dd
Before deleting a line
After deleting a line

d means delete and the second d means the whole line.

Delete several lines

Type a number before dd. This deletes three lines, starting from the current one:

3dd
Deleting three lines

Delete a range of lines

Go to command mode with : and give the range. This deletes lines 5 to 10:

:5,10d
Deleting lines 5 to 10
The file after the range delete

Delete to the end of the file

dG
Deleting to the end of the file
The file after dG

G moves to the last line, and d deletes from the cursor to there.

Delete to the beginning of the file

dgg
Deleting to the start of the file
The file after dgg

Delete lines that contain a word

:g/pattern/d

Replace pattern with the word. For example, delete all lines that contain "Linux":

:g/Linux/d
Deleting lines with a pattern
The file after the pattern delete

g means global. It checks the whole file.

Delete lines that do not contain a word

:v/Linux/d
Deleting lines without a pattern

Good habits

  • Press Esc first. Commands act differently in insert and visual mode.
  • Preview before you delete. Run :g/pattern/ first (without d). Vim then lists all the matching lines.
  • Use u to undo and Ctrl + r to redo.
  • Save with :w, or leave without saving with :q!.

Quick recap

  • dd deletes a line, 3dd deletes three.
  • :5,10d deletes a range.
  • :g/word/d deletes all lines with a word.