How to Remove Lines from Line m to Line n in a Text File Using the vi or vim Editor ?

Introduction

This guide explains how to delete a range of lines — from line m to line n — or all lines in a file using the vi or vim text editor.

Delete Lines from Line m to Line n (where n > m)

To delete lines from line m to line n, use the following command in Normal mode (press Esc first):

1
:m,nd

Where:

  • m is the starting line number.
  • n is the ending line number.
  • d stands for "delete".

Example:

To delete lines from line 10 to line 20:

1
:10,20d

This deletes all lines between and including line 10 and line 20.

Delete from the Current Line to Line n

To delete lines from the current line (where your cursor is) to line n, use:

1
:.,nd

Where:

  • . refers to the current line.
  • n is the ending line number.

Example:

If your cursor is on line 5 and you want to delete from line 5 to line 15:

1
:.,15d

Delete All Lines in the File

To delete all lines from the file (i.e., from the first line to the last line):

1
:1,$d

Where:

  • 1 is the first line.
  • $ refers to the last line.
  • d deletes the range.

References