1.4 β€” Command-Line Mode β€” Ex Commands

1.4 β€” Command-Line Mode β€” Ex Commands#

Command-line mode gives you access to Vim’s powerful Ex commands. These commands handle file operations, search and replace, settings, and much more.

What is Command-Line Mode?#

Command-line mode (also called Ex mode or Cmdline mode) is activated by pressing :, /, or ? from Normal mode. A command line appears at the bottom of the screen where you type commands.

Entry KeyPurposePrompt
:Ex commands:
/Search forward/
?Search backward?

Essential Ex Commands#

File Operations#

CommandAction
:wWrite (save) file
:w filenameWrite to filename
:qQuit
:q!Quit without saving
:wq or :xWrite and quit
:e filenameEdit (open) file
:e!Reload file, discard changes
:r filenameRead file into buffer
:r !commandRead command output into buffer
CommandAction
:10Go to line 10
:$Go to last line
:.Current line
:%All lines (alias for 1,$)

Buffer and Window Commands#

CommandAction
:ls or :buffersList buffers
:b NSwitch to buffer N
:bnNext buffer
:bpPrevious buffer
:bdDelete (close) buffer
:spHorizontal split
:vsVertical split
:closeClose current window
:onlyClose all other windows

Settings#

CommandAction
:set optionEnable option
:set nooptionDisable option
:set option?Show option value
:set option=valueSet option value

Common settings:

:set number          " Show line numbers
:set relativenumber  " Show relative line numbers
:set ignorecase      " Case-insensitive search
:set smartcase       " Case-sensitive if uppercase present
:set hlsearch        " Highlight search matches
:set nohlsearch      " Disable highlight
:set expandtab       " Use spaces instead of tabs
:set tabstop=4       " Tab width
:set shiftwidth=4    " Indent width

Search Commands#

CommandAction
/patternSearch forward for pattern
?patternSearch backward for pattern
nRepeat search (same direction)
NRepeat search (opposite direction)
*Search forward for word under cursor
#Search backward for word under cursor

Search Options#

/pattern\c    " Case-insensitive search
/pattern\C    " Case-sensitive search
/\vpattern    " "Very magic" (regex without escaping)

Clear Search Highlighting#

:noh          " Clear highlight (short for :nohlsearch)

Substitution (Search and Replace)#

The substitute command is one of Vim’s most powerful features.

Basic Syntax#

:[range]s/pattern/replacement/[flags]

Ranges#

RangeMeaning
NoneCurrent line
%All lines
1,10Lines 1-10
.,$Current line to end
'<,'>Visual selection (auto-inserted)

Flags#

FlagMeaning
gGlobal (all occurrences on line)
cConfirm each substitution
iCase-insensitive
ICase-sensitive
nCount matches, don’t substitute

Examples#

:s/old/new/           " First occurrence on current line
:s/old/new/g          " All occurrences on current line
:%s/old/new/g         " All occurrences in file
:%s/old/new/gc        " All occurrences, confirm each
:5,10s/old/new/g      " All occurrences on lines 5-10
:'<,'>s/old/new/g     " All occurrences in selection

Special Replacement Patterns#

PatternMeaning
&Entire matched pattern
\1, \2Captured groups
\uUppercase next character
\lLowercase next character
\UUppercase until \E
\LLowercase until \E

Example: Swap first and last name:

:%s/\(\w\+\) \(\w\+\)/\2, \1/g
" "John Doe" becomes "Doe, John"

The Global Command#

The :g command executes an Ex command on all lines matching a pattern.

Syntax#

:g/pattern/command

Examples#

:g/TODO/d             " Delete all lines containing "TODO"
:g/^$/d               " Delete all blank lines
:g/pattern/p          " Print all matching lines
:g!/pattern/d         " Delete lines NOT matching (or :v/pattern/d)
:g/error/t$           " Copy error lines to end of file
:g/function/normal A; " Append semicolon to lines containing "function"

Command-Line Editing#

While typing in command-line mode:

KeyAction
Esc or Ctrl-cCancel and return to Normal mode
EnterExecute command
Ctrl-bMove to beginning of line
Ctrl-eMove to end of line
Ctrl-wDelete word before cursor
Ctrl-uDelete to beginning of line
Up / Ctrl-pPrevious command in history
Down / Ctrl-nNext command in history
Ctrl-r Ctrl-wInsert word under cursor

Command History#

Vim remembers your commands. Access history with:

Filter history by typing first characters:

:e <Up>    " Cycle through commands starting with :e

External Commands#

Run shell commands from Vim:

CommandAction
:!commandRun command, show output
:r !commandInsert command output
:.!commandFilter line through command
:%!commandFilter buffer through command

Examples:

:!ls                  " List files
:r !date              " Insert current date
:.!sort               " Sort current line (not useful)
:%!sort               " Sort entire file
:'<,'>!sort           " Sort selected lines

Practice Exercises#

Exercise 1: File Operations#

  1. Open Vim: vim
  2. Type some text
  3. :w test.txt to save
  4. :e test.txt to reopen
  5. Make changes, :w to save
  6. :q to quit
  1. Open a file with text
  2. /word to search for β€œword”
  3. Press n to find next occurrence
  4. Press N to find previous
  5. :noh to clear highlighting

Exercise 3: Substitution#

  1. Create text: β€œHello World Hello World Hello”
  2. :s/Hello/Hi/ β€” replaces first Hello
  3. u to undo
  4. :s/Hello/Hi/g β€” replaces all on line
  5. u to undo
  6. :%s/Hello/Hi/gc β€” all in file, with confirmation

Exercise 4: Global Command#

  1. Create a file with various lines
  2. Add β€œTODO” to some lines
  3. :g/TODO/p β€” print TODO lines
  4. :g/TODO/d β€” delete TODO lines
  5. u to undo

Exercise 5: External Commands#

  1. :r !date β€” insert current date
  2. :r !ls β€” insert file listing
  3. Select lines with V
  4. :'<,'>!sort β€” sort selected lines

Summary#

CategoryCommands
File Ops:w, :q, :e, :wq
Search/pattern, ?pattern, n, N
Substitute:%s/old/new/g
Global:g/pattern/command
Settings:set option
External:!command

Command-line mode transforms Vim from a text editor into a text processing powerhouse. Master these commands to handle complex editing tasks efficiently.