Ranges may precede most “colon” commands and cause them to be executed on a line or lines. For example :3,7d would delete lines 3-7. Ranges are commonly combined with the :s command to perform a replacement on several lines, as with :.,$s/pattern/string/g to make a replacement from the current line to the end of the file.
:n,m Range – Lines n-m
:. Range – Current line
:$ Range – Last line
:% Range – All lines in file
:g/pattern/ Range – All lines that contain pattern
vi cheat sheet for Shell Functions
|:! cmd||Executes shell command cmd; you can add these special characters to indicate:% name of current file# name of last file edited|
|:!!||Executes last shell command|
|:r! cmd||Reads and inserts output from cmd|
|:f file||Renames current file to file|
|:w !cmd||Sends currently edited file to cmd as standard input and execute cmd|
|:cd dir||Changes current working directory to dir|
|:sh||Starts a sub-shell (CTRL-d returns to editor)|
let us take the examples of Executing Unix commands in vi:
Any UNIX command can be executed from the vi command line by typing an “!” before the UNIX command.
“:!pwd” – shows your current working directory.
“:r !date” – reads the results from the date command into a new line following the cursor.
“:r !ls -1” – Place after the cursor, the current directory listing displayed as a single column.
|:w file||Write to file|
|:r file||Read file in after line|
|:n||Go to next file|
|:p||Go to previous file|
|:e file||Edit file|
|!!program||Replace line with output from program|
Editing multiple files:
vi file1 file2 file3
:n Edit next file (file2)
:n Edit next file (file3)
:rew Rewind to the first file (file1)
Note: Options given are default.
To change them, enter type :set option to turn them on or :set nooptioni to turn them off.
To make them execute every time you open VI, create a file in your HOME directory called .exrc and type the options without the colon (:) preceding the option :set ai Turns on auto indentation
:set all Prints all options to the screen
:set dir=tmp Sets tmp to directory or buffer file
:set ic Ignores case when searching
:set list Shows tabs (^l) and end of line ($)
:set nu Shows line numbers
:set ro Changes file type to “read only”
:set showmode Indicates input or replace mode at bottom
Some other commands
u – Undo the latest change.
U – Undo all changes on a line, while not having moved off it (unfortunately).
:u – Undo last substituion on line (only one)
^G – Give file name, status, current line number and relative position.
//g – Substitute (on lines x through y) the pattern
with ,`g’ for `global’
:nnpu paste after line nn