Technical Leader

Vim Range

There are numerous commands that can accept a range preceding the command as well as others that range can follow the command. As the name implies you can restrict a command to execute within a particular number of lines.

One such example is with the substitute command. The following command will replace see with saw only in lines 3, 4, and 5.


Some people tend to believe that the second number is a line count, but this is incorrect. As you can see in the preceding example, the first number indicates which line to start at, and the second number specifies which line to stop at.

As I stated in the beginning it is also possible to have a range follow the command. But a note taken from the help:

"The commands that accept a count are the ones that use a range but do not have a file name argument (because a file name can also be a number)."

To copy yet again from the help is an example with the range following the command, this will substitute 'x' with 'X' in the current line and four following lines:

:s/x/X/g 5

Another neat way to specify ranges are used with marks (:help mark). If you have a mark on a line, mark name is 'a', then you can delete the line that the mark is on by doing


You can also use two marks as a range, if you had a mark 'a' and a mark 'c' then you can delete those marks and any lines in between by :'a,'cd<enter>

As I mentioned previously with line numbers, if the mark 'a' is located at a line that is following mark 'c', you will be shown an error message saying that the range is backwards.

Another special character for ranges is '%', this translates to 1,$ (the dollar sign signifies the last line in the file). Using this you can easily delete all lines by: