Vim

Vim: Ranges

You can define a range of lines for many commands in :ex mode.

The general format is :[range][command]

Commands that I use that accept ranges (no doubt there are more):

There are a myriad of ways to define the range.

The most general form is :x,y[command] where x and y represent the starting and ending line numbers respectively.

Ranges are inclusive of the starting and ending lines.

If you omit the second line number the range is simply a single line.

:10,14p prints the lines from 10 to 14 inclusive.

:6p prints line 6

The cursor is moved to the last line of the range (or the first line following if teh range is deleted).

Pattern addressing

You can also use search patterns to specify a line.

:/pattern/p print the next line matching the pattern.

:/pattern1/,/pattern2/p print the lines from the first match of pattern1 to the first match of pattern2.

Line address symbols

There are three special symbols that represent known line positions:

Relative positioning

Using a ; instead of a , to define the range will interpret the second value as an offset from the first line position.

:10;+5p will print lines 10 through 15.

:.;+4p will print the current line and the following 4 lines.

The + is required otherwise the second value is interpreted as an absolute line number.

Getting your bearings

To use these commands you need to know the lines numbers that you want to work with. Here are a few useful methods to help with that.

:set number will display line numbers. :set nonumber turns it off and :set number! will toggle the current setting. I always use line numbers and have this configured in my vimrc file.

The = command prints the matching line number. Without an argument, it prints the line number of the last line in the file. This is a useful way to check the lines you are targetting.

:.= will print the current line number.

:$= will print the last line number of the file.

:= this will also print the last line number in the file (default if you do not specify an argument to =).

:/pattern/= will print the line number that matches the pattern.

Bringing it all together

Tools

Web

Languages

Data