Friday, March 31, 2006

Linux/Unix: vi/vim editing tips

How do I see line numbers ?

:set nu
:set nonu
does the opposite.

Indentation for formatting your programs/scripts

:set autoindent

Saving vi/vim preferences

You can create a file (a hidden file) by name .exrc and write all your ex commands one per line. You can copy-paste the following two lines as .exrc. These options/preferences will work next time you open vi.

set autoindent
set nu

Moving around quickly

* Last line - shift+g
* First line - gg
* One screen forward - ctrl+f
* One screen backward - ctrl+b
* Half screen forward (down) - ctrl+d
* Half screen backward (up) - ctrl+u
* 50th line - 50,shift+g
* Move forward a word - w
* Move back a word - b
* To start of line - 0
* To end of line - $
* Down a line - j
* Up a line - k
* One char left - h
* One char right - l

Deleting content

* Delete a character - x
* Delete a word - dw
* Delete a line - dd

You can multiply these commands with numbers ! e.g. ' 5dw' deletes 5 words.

Chaging content

* Change word - cw
* Change line - cc

Inserting content

You can go into insert mode by following ways

* Insert where cursor is - i
* From start of line - I (shift+i)
* Next line - o
* Previous line - O (shift+o)
* Next character - a
* End of line - A (shift+a)

Copying and pasting

The command to copy content is 'y' (yank).

* Copy a line - yy
* Copy a word - yw

Copy 5 lines - 5yy as explained above. Multiplication applies here as well.
Paste - p
Paste before the cursor position/previous line - P (shift+p)

Content from the last delete (cut) command is stored in a buffer by default. dd followed by p cuts current line and pastes it after the next line. Similarly, x followed by p swaps the chars of a word.

Saving and reading files

* :r filename - read file named filename and insert after current line (the line with cursor)
* :w - write current contents to file named in original vi call
* :w newfile - write current contents to a new file named newfile
* :12,35w smallfile - write the contents of the lines numbered 12 through 35 to a new file named smallfile
* :w! prevfile - write current contents over a pre-existing file named prevfile

Find and replace (substitutions)

This is normally done with ex editor command. Following is the syntax.
For replacing everywhere in the file,
:1,$s/pattern/replacement/g

Explanation

: indicates the start of an ex editor command
1,$ - from the first line to the last line. Alternatively, you can use % (for all lines of a file)
/ used to separate pattern and replacement. Here, you can use regular expressions.
g stands for all occurences of the pattern on a line

No comments: