81

In vi editor how do I go to a particular line ?

For example if I open a file named file.py is there an option for open the file at a particular line or can I open my file and then go to line with keybord shortcut ?

Antoine Subit
  • 2,019
  • 2
  • 11
  • 10
  • 2
    You are welcome here and got your answer. Just an advice for the future: With `man vi` you can read the manual page. With `/line` you can search for occurences of the word `line`, with `n` jump to the next one, just like in `vi`. One of the first matches describes the option you were looking for. This takes less time than searching the web or asking a question here. – Philippos Sep 10 '18 at 15:23

1 Answers1

110

To make vi start at a particular line in a file, add +line_num to the command you use to start vi. Replace line_num with the line number, for example:

vi +14 file.py

You can also use the ex command line to go to a line. (For information about the ex mode, see Use the vi text editor) For instance, if you wanted to go to line 14, you could press Esc and then enter:

:14

There is also a vi command. The G jump (goto) motion takes an optional count prefix, which is the line number to go to. Hence 14G. For the kbd addicts, that's 1, then 4, and then Shift+G.

Antoine Subit
  • 2,019
  • 2
  • 11
  • 10
  • 1
    ...and you'd only press ESC if you weren't already in command mode (or you like your screen to flash) – Jeff Schaller Sep 10 '18 at 14:35
  • You can also move around the file with relative offsets. For example from line 1 you can jump down (`j` or _cursor down_) 13 lines with `13j` (or `13` followed by _cursor down_). Upwards is with `k` or _cursor up_. You can jump up and down by page offsets too with the same principle – roaima Mar 19 '22 at 11:56
  • As long as we’re getting into the weeds: `13+` and `13` *`(Enter)`* will also move down 13 lines, similar to  `13j`, and you can use `13-` (minus) to go up 13 lines. A subtle difference: `j` and `k` are very much like `↓` (Cursor Down) and `↑` (Cursor Up); they will attempt to maintain the horizontal coordinate of the cursor’s position. `+`, `-` and *`(Enter)`*, on the other hand, will move the cursor to the first non-blank character on the destination line. – G-Man Says 'Reinstate Monica' Mar 19 '22 at 17:54