The vi editor is one of the most popular text editors on Unix and Unix-like systems, such as Linux. Whether you're new to vi or just looking for a refresher, these 11 tips will enhance how you use it.
Editing
Editing a long script can be tedious, especially when you need to edit a line so far down that it would take hours to scroll to it. Here's a faster way.
- The command
:set number
numbers each line down the left side.
You can directly reach line number 26 by opening the file and entering this command on the CLI: vi +26 sample.txt
. To edit line 26 (for example), the command :26
will take you directly to it.
Fast navigation
If you notice an error or typo, being able to make a quick fix is important. Good thing vi has it all figured out.
i
changes your mode from "command" to "insert" and starts inserting text at the current cursor position.a
does the same, except it starts just after the current cursor position.o
starts the cursor position from the line below the current cursor position.
Delete
Understanding vi's delete function so you don't accidentally press a key and permanently remove a line, paragraph, or more, is critical.
x
deletes the character under the cursor.dd
deletes the current line. (Yes, the whole line!)
Here's the scary part: 30dd
would delete 30 lines starting with the current line! Proceed with caution when using this command.
Search
You can search for keywords from the "command" mode rather than manually navigating and looking for a specific word in a plethora of text.
:/<keyword>
searches for the word mentioned in the< >
space and takes your cursor to the first match.- To navigate to the next instance of that word, type
n
, and keep pressing it until you get to the match you're looking for.
For example, in the image below I searched for ssh
, and vi highlighted the beginning of the first result.
After I pressed n
, vi highlighted the next instance.
Save and exit
Developers (and others) will probably find this next command useful.
:x
saves your work and exits vi.
-
If you think every nanosecond is worth saving, here's a faster way to shift to terminal mode in vi. Instead of pressing
Shift+:
on the keyboard, you can pressShift+q
(or Q, in caps) to access Ex mode, but this doesn't really make any difference if you just want to save and quit by typingx
(as shown above).
Substitution
Here is a neat trick if you want to substitute every occurrence of one word with another. For example, if you want to substitute "desktop" with "laptop" in a large file, it would be monotonous and waste time to search for each occurrence of "desktop," delete it, and type "laptop."
- The command
:%s/desktop/laptop/g
would replace each occurrence of "desktop" with "laptop" throughout the file; it works just like the Linuxsed
command.
In this example, I replaced "root" with "user":
These tricks should help anyone get started using vi. Are there other neat tips I missed? Share them in the comments.
42 Comments