Learning Vim Editor – Part 2

2. Part 2: ex

ex is the underlying editor for vi. It offers a richer set of commands to do multi-line editing.

The general syntax for ex commands is: [scope]command[command argument], where scope specifies the range of lines that you want command to have effect on. A command without a scope is assumed to affect the current line. I’ll try to summarize scope, command and command argument in three separate subsections

2.1. Scope

Scope is represented by specifying two lines: Start Line and End Line. Command will only operate on lines within this bound. You can use any of the following methods to identify a target line, and you can use symbol ‘,’ to combine two lines to represent the scope.(Note: You can also use ‘;’ to combine two lines. The subtle difference lies in how current line anchor is defined when searching for Start Line and End Line)

    • Explicit line numbers: num1 represents line num1
    • Symbols: You can use the following symbols to specify a line relative to current line.
      . Current line
      $ Last line of file
      % Every line in the file
      symbol {+/-} num The line represented by symbol with offset {+/-}num

    • Search Patterns: /pattern/ represents the next line containing /pattern/. You can also use {+/-} to do offset.

2.2. Command

Here is a list of Commands:

:num Go to line num
:p Print lines
:# Print lines with line number
:= Print line number
:g/pattern/ cmd Run cmd on each of the lines containing pattern
:g/pattern/ cmd Run cmd on each of the lines not containing pattern
:d Delete
:m target line Move to target line
:co/t target line Copy to target line
:s/pattern1/pattern2/ Replace pattern1 with pattern2
:cmd1{|}cmd2 Combine multiple commands. Run cmd2 after cmd1
:w file Save to file but not quit
:r file Read file and append
:e file Open file to edit.
:q Quit if you have not made any edits

2.3. Command Arguments

Command argument format usually depends on the specific command. For example, :w takes a string to represent the name of the file, while :m takes as argument another line specified by one of the methods described in Scope. vi maintains two file names accessed most recently by :e, and there are two symbols that can be used in command arguments to represent them:

% Current file name
# Alternative file name