Vi  Editor

UNIX has a number of editors that can process the contents of text file, whether those files contain data, source code, or sentences. There are line editors, such as "ed" and "ex", which display a line of the file on the screen; and there are screen editors, such as "vi" and "emacs", which display a part of the file on your terminal screen. Text editors based on the X Window System are also commonly available, and are becoming increasing popular.
Vi (visual editor) is the most useful standard text editor on UNIX OS.

1. Opening and Closing Files

vi filename(s) open file, if it doesn't exist - creates new one
vi +  filename open file, set cursor at the last line of filename
vi +32  filename open file, set cursor at line number 32
vi /pattern  filename open file, set cursor on first occurrence of pattern
vi -o2  file1 file2 open two files, screen is split in two parts
vi -t  tag open file, cursor position on the first occurrence of tag (from tag-file)
vi -c  command  filename open file, executes command(s)
vi -r list of swap files
vi -r  filename recover file after system crash
vi -h short description of all possible options
top

2. Modes

1. Command mode   you start out in command mode, where every keystroke represents command.
 To get the command mode you have to press ESC.
2. Insert mode everything you type becomes text in your file.
3. Last line mode execute command of "ex" editor (:, /, ?)
top

3. Insert Mode

i insert text before position of cursor
I insert text at the beginning of current line
5i*<ESC> insert five asterisks
a append text after position of cursor
A append text at the end of current line
5a*<ESC> append five asterisks
o open new line below cursor
O open new line above cursor
top

4. Saving and Quitting a File

:w save
:w! to overwrite the existing file
:wq save and quit
ZZ save and quit
:w newfile to save the edited version in a new file
:e! returns to the last saved version on the file
:q quit from the file
:q! quit the file (without saving edited info)
<CTL> Z to suspend vi and return to the UNIX prompt, type fg - to return to "vi" session
!sh to suspend vi and return to the UNIX prompt
top

5. Vi Commands

There are several ways to tell vi that you want to begin insert mode. One of the most common is to press “i”. To tell vi that you want to stop inserting text, press <ESC>.
 
Moving the Cursor
h left, one space
j down, one line
k up, one line
l right, one space (you can also use the cursor arrow keys)
 
Numeric Arguments
4l moves cursor four characters left
3k moves cursor 3 lines up
 
Movement Within a Line
0 move to beginning of line ( <CR>a )
^ move to first non-blank character of current line
$ move to the end of line. ( <CR>e )
 
Movement by Text Blocks
You can also move the cursor by blocks of text: word, sentences, paragraphs, etc
w moves the cursor forward one word
5w moves the cursor forward five words
b to move backward by word
e moves to the last character of current word
5B moves back five words, not counting punctuations
G move to last line
8G move to 8 line
+ move to first character of next line
- move to first character of previous line
( move to beginning of current sentence
) move to beginning of next sentence
{ move to beginning of current paragraph
} move to beginning of next paragraph
8| move to column 8 of current line
/pattern to search (forward) for the pattern and move cursor to it
?pattern to search (backward) for the pattern and move cursor to it
n repeat previous search forward
N repeat previous search backward
fT find the first occurrence of "T" in current line and move cursor to it
 
Scrolling
<CR>f scroll forward one screen
<CR>b scroll backward one screen
<CR>d scroll forward half a screen
<CR>u scroll backward half a screen
z move current line to top of screen and scroll
z. move current line to center of screen and scroll
z- move current line to bottom of screen and scroll
 
Deletion Commands
x delete single character
5x delete 5 characters (forward)
dw delete word
3dw delete 3 words (forward)
db delete word (backward)
3db delete 3 words back
dd delete entire line
3dd delete 3 line (start from current)
D delete from cursor position to end of current line
d$ delete from cursor position to end of current line
d0 delete from cursor position to beginning of line
 
Change Commands
r replace one character
5s change 5 characters.
5r* replace 5 characters for 5 asterisks
R replace from cursor to end of line
C change from cursor position to end of line
c$ change from cursor position to end of line
c0 change from cursor position to beginning of line
dwelp exchange two words
xp exchange two characters
 
Copying text
y copy single character (forward)
yh copy single character (backward)
5yl copy 5 characters
yw copy one word forward
yb copy one word backward
2yw copy 2 words forward
3yb copy 3 words backward
yy copy entire line
Y copy entire line
5yy copy 5 lines starts from current
y$ copy from cursor position to end of current line
y0 copy from cursor position to beginning of current line
 
Paste
p place text from buffer below of cursor position
P place text from buffer above of cursor position
 
Operations
u undo last action
U restore line to original state
. repeat previous action
J join current and next line
~ toggle case
<CR>R undo undo
top

6. Marking Your Place

          During a vi session, you can mark your place in the file with an invisible "bookmark", perform edits elsewhere, then return to your marked place (in command mode).
ma masks the current position with a (a can be any letter)
`a moves the cursor to the character marked by a (backquote)
`` returns to the exact position of the previous mark
'a (apostrophe) moves the cursor to the first character of the line marked a
'' returns to the previous mark (two single quotes)
top

7. Yanking to Named Buffers

          You must put (p or P) the contents of the unnamed buffer before you make any other edit, or the buffer will be overwritten. You can also use y or d with a set of 26 named buffers (a-z) that are specifically available for copying and moving text. If you name a buffer to store the yanked text, you can retrieve the contents of the named buffer at any time during your editing session.
          To yank into a named buffer, precede the yank command with a double quote (").
"xyy yank current line into buffer x
"z7yy yank 7 lines (start is current) into buffer z
"a5dd delete 5 lines and yank them into buffer a
"A2yy add 2 lines to named buffer a
"a2w yank 2 words into buffer a
top

8. Recovering Deletions

          When you deleted text, it is saved in a buffer (a place in stored memory). You can access the contents of that buffer and put the saved text back in your file with the put command (p or P). There are 9 numbered buffers (1-9). The last delete is saved in buffer 1, the second-to-last in buffer 2, and so on.

"2p - to recover your second-to-last deletion from buffer 2.

          If you're not sure which buffer contains the deletion you want to restore, you don't have to keep typing "np over and over again. If you use the repeat command (.), with p after u, it automatically increments the buffer number. As a result, you can search through the numbered buffers as follows:

"1pu.u.u   etc.
:display (:dis for short) - to see contents of all buffers
top

9. Last Line Mode

:set number (:set nu for short) display all line numbers
:set nonumber (:set nonu for short) unset line numbers
 
Commands
Delete d delete line(s)
Move mo (or m) move line(s)
Copy co (or t) copy line(s)
 
Line Addresses
For each command in last line mode, you have to specify an "address".
:. symbol of current line
:$ symbol of last line
:1,$ entire file
:% symbol of entire file
:0 line number zero
:1,3 lines from 1 to 3
:4,. lines from 4 to current
   
:10d delete line number 10
:2,7d delete lines from 2 to 7
:.,.+10d delete 10 lines from current to current + 10 lines
:12,$mo.-2 move lines 12 through the end of the file to two lines above the current line
:2,8m20 move lines 2-8 to line number 20
:1,10co20 copy lines 1-10 to line number 20
:5co0 copy line number 5 to the very start of file
 
Search Pattern
:/pattern/d delete the line containing pattern
:/pattern/+1 delete the line below the next line containing pattern
:/pattern1/,/pattern2/d delete from the first line containing pattern1 through the first line containing pattern2
:.,/pattern/m20 take the text from the current line (.) through the first line containing pattern
 and put it after line 20
:/pattern/;+10d delete the text from first line containing pattern + 10 lines below this line
 
Global Searches
:g search for all lines containing some pattern
:g! search for all lines that do not contain pattern
:g/pattern/ finds ( move to ) the last occurred of pattern
:g/pattern/p find and display all lines containing pattern
:g!/pattern/nu finds and display all lines that don't contain pattern; also displays the line
 number for each line found
:5,100g/pattern/p finds and display all lines between lines 5 and 100 containing pattern
 
Combining Commands
|  - (vertical bar) is a command separator
:1,3 mo 10 | g/pattern/nu move lines 1 through 3 after line 10, and then display all lines containing pattern
 
Saving Part of File
:.,20 w >> filename append these line to the filename
:100,$ w nefile saves from line 100 to end of file in newfile
 
Copying a File into Another File
:read filename copy contents of filename to the current opened file below cursor position
:$r /home/data place the read-in file at the end for the current file
:0r /home/data place the read-in file at the very beginning of the current file
:0r !date place the output from command "date" to the very first line
 
Working with Named Buffers
:5,20ya a yank lines 5-20 into named buffer a
:10,15d a delete lines 10 - 20 into named buffer a
:2,5ya A append lines 2 - 5 to named buffer a
:pu a put contain of buffer a below cursor position
top

Global  Replacement


Often enough it happens that you have to go back and change what you've already written, and you need to make the changes in several places. The way to make these changes is with a powerful change command called Global replacement.
Global replacement "uses" two ex commands:
:g (global) and :s (substitution).
Syntax s/old/new/ ( slash is optional delimiter )
 
:s/One/ONE/ substitute first occurrence of One to ONE on the current line
:s/One/ONE/g substitute all occurrences of One to ONE on current line
:1,$s/old/new/g substitute all occurrences of old to new (hole file)
:%s/old/new/gc substitution with confirmation.
 
:g/pattern/s/old/new/g the first "g" tells the command to operate on all lines of a file. pattern identifies the lines on which a substitution is to take place. On those lines containing pattern, "ex" is to substitute (s) for "old" the characters in "new". The last "g" indicates that the substitution is to occur globally on that line.
top
Pattern-Matching Rules
In making global replacements, Vi allow you to search not just for fixed strings of characters, but also for variable patterns of words, referred to as REGULAR EXPRESSIONS. For the most part, the same regular expressions work with other UNIX programs such as grep, sed, and awk.
Regular Expressions are made up by combining normal characters with a number of special characters called "metacharacters".
top
Metacharacters Used in Search Patterns
. matches any single character except a newline
p.p matches pap,pbp,pep etc
* matches zero or as many as there are of the single character that immediately precedes
:s/UNIX.*/UNIX/ removes all characters after UNIX
^ matches beginning of line
^Part matches Part when it occurs at the beginning of a line
^... matches the first three characters of a line
$ matches end of line
UNIX:$ matches UNIX: when it occurs at the end of line
\ treats the following special character as an ordinary character
\. matches an actual period instead of "any single character"
\* matches an asterisk itself
[ ] matches any one of the characters enclosed between the brackets
[abc] matches a or b or c
p[aeo]t matches pat or pet or pot
 
A range of consecutive characters can be specified by a hyphen.
[A-Z] any uppercase letter from A to Z
[0-9] any digit from 0 to 9
 
\{ \} matching a precise number of characters
X\{1,10\} matches from one to 10 consecutive X's
[a-zA-z]\{10\} matching exactly 10 alphabetic characters
a\{5,\} matches at least five consecutive a characters
:1,$s/.\{5\}$// delete the last 5 characters from each line
:1,$s/^.\{10\}// delete the first 10 characters from each line
 
Most metacharacters lose their special meaning inside brackets. You need escape just  : \ - ].
A caret (^) has special meaning only when it is the first character inside the bracket. Any one character not in the list
[^a-z] matches any character that is not a lowercase letter
\( \) Saves the pattern enclosed between \( and \) into a special holding space or "hold buffer." Up to 9 pattern can be saved in this way on a single line
:%s/\(OS\) \(UNIX\)/ \2 \1/g replace all occurrences of OS UNIX to UNIX OS. OS is saved into "hold buffer" 1, and UNIX into buffer 2
:s/\(abc\)\1/alphabet/ changes abcabc to alphabet
 
\< \> matches characters at the beginning (\<) or at the end (\>) of a word
\<ab matches only words that begin with ab
ac\> matches only words that end with ac
\<word\> exactly word "word"
top

POSIX Bracket Expressions

Class Matching Characters
[:alnum:] Alphanumeric characters
[:alpha:] Alphabetic characters
[:blank:] Space and tab characters
[:cntrl:] Control characters
[:graph:] Printable and visible (non-space) characters
[:lower:] Lowercase characters
[:print:] Printable characters (includes whitespace)
[:punct:] Punctuation characters
[:space:] Whitespace characters
[:upper:] Uppercase characters
[:xdigit:] Hexadecimal digits
top
Pattern-Matching Rules
When you make global replacements, the regular expressions carry their special meaning only within the search portion (the first part) of the command
:%s/1\. Start/2. Next, start with $100/ . and $ in second part of command is literal characters
:%s/[ABC]/[abc]/ replace all A or B or C to [abc] literally
 
To solve problems like this, you need a way to specify variable replacement string
\n is replaced with text matched by the nth pattern previously saved by \( and \)
\ treats the following special character as an ordinary character. To specify a real backslash, type two in a row (\\).
& is replaced with the entire text matched by the search pattern when used in a replacement string. This is useful when you want to avoid retyping text:
:%s/Robert/& Frost/  
:1,10s/.*/(&)/  
~ remembers replacement text specified in the last substitute command (tilda)
\u or \l causes the next character in the replacement string to be changed to uppercase or lowercase, respectively
  :s/yes, doctor/\uyes, \udoctor
\U or \L causes that all following characters are converted to uppercase or lowercase
  :%s/Fortran/\UFortran/ or simpler :%s/Fortran/\U&/
\e or \E end of \U or \L
top

Examples:
:%s;/home/tim;/home/linda;g    modify a list of pathnames in a file
:%s;RETURN;<I>&</I>;g put HTML italicization codes around the word RETURN
:1,10s/\./;/g change all periods to semicolons in line 1 to 10
:%s/[Hh]elp/HELP/g  or  
     :%s/[Hh]elp/\U&/g change all occurrences of the word help or Help to HELP
:%s/ */ /g replace one or more spaces with a single space
:%s/\([:.]\) */\1 /g replace one or more spaces following a period or a colon with two spaces
:g/^$/d delete all blank lines
:g/^[ tab]*$/d delete all blank lines, plus any lines that contain only whitespace
:%s/^ *\(.*\)/\1/ delete all leading spaces on every line
:%s;^;//; or :1,20s;^;#; insert // ( or # ) at the beginning of lines
:.,+5s/$/./ add a period to the end of the next six lines
:%s/.*/\U&/ or :%s/./\U&/g change every word in a file to uppercase
top