Moving around in the file



Last revision August 2, 2004

Table of Contents:
  1. Editor choices on Unix
  2. Characteristics, advantages, and disadvantages of vi
  3. Basic text editing operations in vi
  4. Regular expressions
  5. File searching with grep
  6. More about regular expressions
  7. Intermediate text editing with vi
  8. Vi Quick Reference

On this page, "down" or "forward" in the file means to move to a position FURTHER from the beginning of the file. "Up" or "backward" means to move to a position CLOSER to the beginning of the file.

The file, which is simply a byte stream to Unix, is separated by vi into lines according to the presence of "new-line" characters (a non-printing character). The end of a line is the last character in the line before the new-line, not the last column on the screen.

For moving the cursor around on the screen without changing your location in the file vi does not need special cursor arrow keys. Instead, the h, j, k, and l (letter "ell", not numeral "one") keys (lowercase only) control the cursor movement.

If your terminal has arrow keys, and the terminal type has been correctly specified, they should also work.

h moves the cursor left, j moves it down, k moves it up, and l moves it right, as shown in this schematic:

                k

        h               l

                j

The j and k keys try to maintain the cursor in the same column on the new line. However, if you move to a line with fewer columns, then the cursor moves left to the end of the line. If the cursor is already on the end of the line, a j or k command keeps the cursor on the end of the new line, even if that is a new column position.

Each time you press h, j, k, or l, it moves the cursor one position. You can also move in bigger chunks.

Other commands let you move the cursor within a line.

The w, b, and e keys (and their uppercase variants) continue onto the next line when you reach the end of one line.

You can move the window (screen) to show another set of lines in the file.

You can use a command to go to a specific line in the file. For this purpose, it may be helpful to see line numbers on the screen. To turn on line numbering on screen, use

:set number <CR>

To turn off line numbering, use

:set nonumber <CR>

These commands do not put line numbers into the file, only on the screen.

To just find out the number of the line where the cursor is and total size of the file, use CTRL-G.

To go to line number n in the file, use the command nG, substituting the actual line number you want for n. Vi will try to move the screen so the desired line is in the middle. A plain G with no preceding number goes to the end of the file.

An alternate way to move to a desired line n in the file is the command

:n<CR>