Top 11 vi tips and tricks

Whether you're new to vi or looking for a refresher, these shortcuts will quickly make you a power user.
434 readers like this
434 readers like this
How do we fix the state of technical documentation?

Victor via Flickr. CC BY 2.0

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.

  1. The command :set number numbers each line down the left side.

the :set number command

opensource.com

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.

using the :set number command

opensource.com

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.

  1. i changes your mode from "command" to "insert" and starts inserting text at the current cursor position.
  2. a does the same, except it starts just after the current cursor position.
  3. 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.

  1. x deletes the character under the cursor.
  2. 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.

  1. :/<keyword> searches for the word mentioned in the < > space and takes your cursor to the first match.
  2. 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.

Searching for "ssh"

opensource.com

After I pressed n, vi highlighted the next instance.

using the 'n' command to find the next instance of "ssh"

opensource.com

Save and exit

Developers (and others) will probably find this next command useful.

  1. :x saves your work and exits vi.

the :x command

opensource.com

  1. 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 press Shift+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 typing x (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."

  1. The command :%s/desktop/laptop/g would replace each occurrence of "desktop" with "laptop" throughout the file; it works just like the Linux sed command.

In this example, I replaced "root" with "user":

typing the substitute command

opensource.com

the substitute command result

opensource.com

These tricks should help anyone get started using vi. Are there other neat tips I missed? Share them in the comments.

OpenStack enthusiast. Linux and Networking guy. Just trying to give my two cents in this billion-trillion dollar "Open Source" world.

42 Comments

FYI: ZZ is an alias for :x and :wq as well

Copy-paste without the mouse (or if you are in a terminal/ssh without a mouse)

Press v, move around with arrow keys or h,j,k,l to select text. Press y to "yank" (copy) then move cursor to new place and press p to "pull".
Can also press d to delete instead.

I have not a lot of experience with vi before, but it always attracted me by its simplicity. Thanks for your article my relations with vi will be more friendly)) :x

I’m glad to hear that! I tried to include all the commands that I use, hopefully this should be enough to just get started with vi :-)

In reply to by Tom

I used to be able to copy and paste to via over ssh, and now it changes to visual mode and it won't accept a paste.

Hi,
It does change to visual mode, altough i was able to paste it by typing p. I’m not sure if different linux distros behave differently in this case.

In reply to by cybernard (not verified)

Hi, to leave without saving changes:
:q!

It is perhaps useful to mention that l moves to the right, j moves down, k moves up, and h moves left. Any of these keys can be prefaced with a number, so 26j moves you 26 lines down. Also $ moves to the end of the line and 0 to the start. I think knowing these keys are fundamental to being able to navigate in vi.

You mentioned substitution, but you can also use regular expressions to search. :/ brings you to the start of the line containing the text, and n jumps to each place where the text occurs, in turn.

When using :q to quit, vi will not let you if you have changed something. Use :q! to force quit without saving.

I also use yy a lot. It copies lines into the buffer, which can then be pasted with p. Like many other commands, it takes an optional number to preface, like 6yy to copy 60 lines. p also takes numbers. When you use dd to delete lines, they also go into the buffer and can be pasted in with p. p pastes the number of lines in the buffer, but if a number is used, the buffer lines will be pasted multiple times.

The vi editor has been a constant throughout my IT career having started out in Unix. It was the one editor I could be sure was available regardless of the Unix or Linux variant I was on. Here are a few useful vi commands I regularly use (and have done for nearly 30 years):-

To Save and exit vi quickly, use:
Shift + ZZ

To delete from the current cursor position to the end of the line:
Shift + D

To delete a specific number of line e.g 5 lines, use:
5dd

To delete a word:
dw

To append at the end of a line:
Shift + A

To copy lines (yank and put) position the cursor on the line to copy and then use:
yyp

To copy 5 lines use:
5yyp

Note, when copying lines, after you have y (yanked) the lines, you can position the cursor to where you need to in the file before you p (put).

To go to the end of the file:
Shift + G

to go to a specific line number e.g line 22:
22 Shift+G

There are a gazilion other features in vi, but you generally tend to find the most useful ones and stick with them. However, from time to time you come accross a scenario in which you require something special and vi always seems to have an answer for it. These days, I like to use vim (Vi Improved) as it adds some nice extras including text highlighting

One thing I don't see mentioned and would be a bonus within the deleting section is "u" this allows you to UNDO any edits ... for instance deleting 6 lines rather than one ... each "u" will delete the recent edits one at a time all the way back to the last save. That said its good to have a refresher on VI but really nice when a useful option is exposed after years of using the same old options. One that may have been mentioned but here it is again is ":set list" this is really useful when debugging a file with some spurious hidden character embedded that 'cat' or 'grep' just does not expose.

That's a very useful tip, I will definitely use this, thanks!! :)

In reply to by Laurie Baker (not verified)

Run 'vimtutor' to learn a lot more useful tips for vi/vim.

Move between your changes by g+ for newer changes and g- for older changes in your undolist. Vim's integrated time machine ;)
And don't forget about :h g+ and :h g- and :h undolist

ah, so many with vi. you can also use anchors/tags to control specific things. e.g.
:10,90 d -- delete lines 10 to 90
:5,90 s/this/that/g -- do a 'that' for 'this' replacement but only on certain lines.
dot (.) is an alias for the current line, $ is the end of the file
:.,$ s/argh/grah/g -- subsitite from this line to the end of the file.

if you're on a blank line and in command mode, type ! and some command and the output will be put in as text (handy for when writing docs about how commands do things)

~
~
~
:.,$!ifconfig -a

enp0s3: flags=4163 mtu 1500
inet 10.0.2.15 netmask 255.255.255.0 broadcast 10.0.2.255
...
...
...

~
~

inj command mode, ^g (control g) to get what line/char position you're currently at on the lowest line:
"[No Name]" [Modified] 30 lines --10%--

oh and using ~ in command mode to shift upper to lower or vice versa

The period (.) is one of my favorite, little-known vi commands. It repeats the previous action, like changing a word, deleting a line, or putting a paragraph. It's great for repetitive tasks you want to do selectively. For example, to change every instance of "the" to "THE" do this:
/the
cwTHE
n
.
n
.
This finds and changes each instance of "the" one at a time. If you don't want to change an instance, just hit n again to continue to the next one.

:set nu same as :set number
:set nonu "unsets" numbers (restores normal gutter)

There's a game called VIM Adventures that has a fun way to learn VIM.
The first few levels are free.

Control + g will display the file's name, the line number in the file where your cursor rests, the total number of lines in the file, and the ratio (e.g., 27%).

Rather than % in a substitute command, you can also use line numbers. :1,5s/Foo/Bar/g will replace Foo with Bar in the first 5 lines of the file. You can use . as the line number containing the cursor and $ as the last line in the file, so :.,$s/Foo/Bar/g replaces Foo with Bar from your current line until the end of the file.

As you mention, :35 will take you to line 35. Math is also supported, so :.+5 takes you down 5 lines and :.-24 up 24 lines. :.,.+20s/Foo/Bar/g replaces Foo with Bar over the next 21 lines.

Fun with Line Numbers! :-)

My favorite is '%s' global search and replace.
Funny story, when I was a wee IT lad, my manager had me interview a fellow. I came back two minutes later and he asked me what happened?
I merely stated,"he didn't know Unix" although it was one his resume.
I had him sit at the shell and show me how to do some vi commands. I figured if you say you know Unix, you should know VI. Always saved my time in interviews.

vi is so powerful, but sometimes I mess up a file I'm editing so bad I just want to start over:

:e! throws away all your changes since the last save

Thank you for sharing. A few of them saved my life many a times :)

Great article. Vim, one of my favourite editor I have used with linux

Creative Commons LicenseThis work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License.