Book HomeLearning the vi EditorSearch this book

3.4. Movement by Line Number

Lines in a file are numbered sequentially, and you can move through a file by specifying line numbers.

Line numbers are useful for identifying the beginning and end of large blocks of text you want to edit. Line numbers are also useful for programmers, since compiler error messages refer to line numbers. Line numbers are also used by ex commands, which you will learn in the next chapters.

If you are going to move by line numbers, you must have a way to identify them. Line numbers can be displayed on the screen using the :set nu option described in Chapter 7. In vi, you can also display the current line number on the bottom of the screen.

The command CTRL-G causes the following to be displayed at the bottom of your screen: the current line number, the total number of lines in the file, and what percentage of the total the present line number represents. For example, for the file practice, CTRL-G might display:

"practice" line 3 of 6 --50%--

CTRL-G is useful either for displaying the line number to use in a command or for orienting yourself if you have been distracted from your editing session.

Depending upon the implementation of vi you're using, you may see additional information, such as what column the cursor is on, and an indication as to whether or not the file has been modified but not yet written out. The exact format of the message will vary as well.

3.4.1. The G (Go To) Command

Figure You can use line numbers to move the cursor through a file. The G (go to) command uses a line number as a numeric argument and moves directly to that line. For instance, 44G moves the cursor to the beginning of line 44. G without a line number moves the cursor to the last line of the file.

Typing two backquotes (` `) returns you to your original position (the position where you issued the last G command), unless you have done some edits in the meantime. If you have made an edit, and then moved the cursor using some command other than G, ` ` will return the cursor to the site of your last edit. If you have issued a search command (/ or ?), ` ` will return the cursor to its position when you started the search. A pair of apostrophes (' ') works much like two backquotes, except that it returns the cursor to the beginning of the line instead of the exact position on that line where your cursor had been.

The total number of lines shown with CTRL-G can be used to give yourself a rough idea of how many lines to move. If you are on line 10 of a 1,000 line file:

"practice" line 10 of 1000 --1%--

and know that you want to begin editing near the end of that file, you could give an approximation of your destination with 800G.

Movement by line number is a tool that can move you quickly from place to place through a large file.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.