vi notes

For me, vi has to be the best text editor out there for Linux. Sure, there are countless other editors like pico, emacs and the like but none with the power that vi offers, in my opinion of course. Admittedly, vi isn’t very user friendly and it has a steep learning curve. It comes pre-installed in nearly all Linux based distros by default so you can rest assured that you will have all of vi’s editing powers at your finger tips, literally, 😉

Over the years that I’ve spent using vi, I have collected some knowledge that I would like to share. This is not meant to be a tutorial or even a guide per se. Its just a bunch of stuff that has made my experience with vi that much more enjoyable. I guess you can call them, my “vi notes“. I am assuming that you have some basic experience with Linux and especially vi. You also need to know vi’s two modes, command and insert and how to get in and out of them at will. If you don’t, then these notes aren’t for you.

On to the notes already!


Copy and Paste

  1. Press v
    (enters visual mode so you can highlight stuff)
  2. Use the arrow keys to highlight
    (or the h,j,k,l,w,b,$ keys )
  3. Press "y" to yank, "p" to paste.
    (shift-p to open up a line above and paste)
  • Copy a word by using "yw"
  • Copy a line by using "yy"
  • Copy from cursor to end of line by using "y$"

Search and Replace:

  • Search from current line to end of file

    : ,$s/search/replace/gc

    (the gc means global and confirm)

  • For example, to substitute all matches of the URL microsoft.com with the URL linux.org

    : %s/microsoft.com/linux.org/g

Navigation:

  • Go up - k
  • Go down - j
  • Go left - h
  • Go right - l
  • Go right a word - w
  • Go left a word - b
  • Go to beginning of file - gg
  • Go to end of file - G (thats a capital "g")
  • Go to beginning of non-whitespace part of line - ^
  • Go to end of line - $

vi Options:

  • Display all options:
    :set all
  • Show line Numbers:
    :set nu
  • Remove line Numbers:
    :set nonu

Open a Shell from within vi:

:shell

To come back to VI from the shell type "exit" or "CRTL-D"

Insert output of command:

:r ! date
(the Linux command "date" was used in this example but most any command can be substituted)

List contents of your current directory on the screen

:!ls
(the possibilities are endless)

Jump immediately to a particular pattern from the shell (comes in handy if you know what you need to fix)

vi +/pattern filename

For example, if I wanted to open the file foobar.sh at the point where clusterfsck shows up, type:

vi +/clusterfsck foobar.sh

Thats it for now people. If you have a vi tip that you would like to share, please do. Damn, if you read this far, then consider yourself to be a geek!


About this entry