Monday, February 18, 2008

Quick tutorial on using vi

Open your favorite text file in vi:

% vi myfile.txt

Navigate to the text you wish to change using hte h, j, k, and l keys

j goes down
k goes up
h goes left
l goes right

Don't worry...it gets super intuitive after a while!

To jump to the last line of the file, type G

To jump to the first line of the file, type 1G

To insert some text starting at your cursor, type i, then type your text. Press Escape when you're done with your insert.

To delete the character under the cursor, type x

To undo what you last did, type u

To save your file, type :w

To save your file and quit, type either :wq or ZZ

To save without quitting, type :q!

To overwrite a file, even though it's listed as read-only, type :w!
The ! means you really, really mean it!!

To delete the rest of a word from where your cursor is, type dw

To change the rest of the word from where your cursor is, type cw. Press Escape when you're done with your insert.

To delete from where your cursor is to the end of the line, type d$

To change the text from your cursor to the end of the line, type c$. Press Escape when you're done with your insert.

To repeat your last command, type .

To search for a string in the file, type /, then type your string. Example: /Target
You can use ^string to find a string only at the beginning of the line, and string$ to find a string only at the end of the line.
To repeat your search, type n


NOW HERE'S WHERE IT STARTS TOTALLY ROCKING!!!

To delete from wherever you are, all the way to the next occurance of a string, type d/

To change the text from your cursor to the next occurance of a string, type c/

Global search and replace.

Type %s/string/somethingelse/g to find all occurrences of "string" and to change it to "somethingelse"

The /g on the end makes it do it to the whole file. If you leave that off, it will just do it to the current line.

You can also add multipliers to your commands.

To delete from your cursor 5 characters, you don't need to type xxxxx. Just type 5x, and it will do the x 5 times.

Same works for changing/deleting words. 4dw deletes 4 words starting at the word you're on.

1 comment:

Jonathan said...

Hey, you should check out the vi tutorial at unixlessons.com ;)