Ex Commands, Ranges, and :global
Edit whole regions of a file from the command line: line ranges, :d :m :t :j and :normal, the :global command, :sort options, and filtering text through shell tools.
By The Dark DebuggerUpdated 21 min read
Everything you type after a : is an Ex command, and most of them accept a range: the
lines to work on. This article covers how ranges are written, the line-editing commands
that use them (:d, :m, :t, :j, :normal), the :global command that runs any of
them on matching lines, :sort, and filtering text through shell programs. It builds on
:s from Search and Replace and on the :'<,'> range
you met in Visual Mode.
Why line-oriented commands matter
Picture a 4,000-line application log during an incident. You want only the ERROR lines,
without timestamps, grouped and counted. Or a config file where the [cache] section has to
move above [database], or an inventory where every decommissioned host must go and every
remaining one needs a domain suffix.
You could do all of that with Normal-mode keystrokes, one line at a time. Ex commands do it
in one line each, by describing which lines and what to do, and they work the same on 10
lines or 100,000. They are also the commands that :global, :argdo and macros build on, so
the time spent here pays off in every later article.
Anatomy of an Ex command
:[range]command[!] [arguments]- range: which lines. Leave it out and each command has a default (usually the current line).
- command:
d,m,t,s,sort,normal,w, … Most have a short form. !: a variant, such as:sort!(reverse) or:w!(force).
To see what a range covers before you change anything, use :# (or :number), which prints
the lines with their numbers. All examples here use this app.ini:
; checkout service configuration
[server]
port = 8080
workers = 4
[database]
host = db-primary.internal
port = 5432
pool_size = 10
[cache]
host = redis.internal
port = 6379
ttl = 300
[logging]
level = debug
format = json:3,4# 3 port = 8080
4 workers = 4Writing ranges
| Range | Lines |
|---|---|
5 | line 5 |
. | the current line |
$ | the last line |
% | every line (same as 1,$) |
3,7 | lines 3 to 7 |
.,+2 | the current line and the two after it |
$-1,$ | the last two lines |
'a,'b | from mark a to mark b |
'<,'> | the last Visual selection (whole lines) |
/pat/ | the next line matching pat |
?pat? | the previous line matching pat |
/pat/+1 | the line after the next match |
Offsets like +1 and -1 work after any address. With the cursor on line 6:
:.,+2# 6 [database]
7 host = db-primary.internal
8 port = 5432:$-1,$# 17 level = debug
18 format = jsonMarks work as addresses too. I set mark a on line 7 (:7, then :mark a, the same as ma
in Normal mode), moved to line 9, and printed from the mark to the cursor:
:'a,.# 7 host = db-primary.internal
8 port = 5432
9 pool_size = 10Pattern ranges, and why ; beats ,
Patterns make ranges independent of line numbers, which is what you want in config files
that change. "From the [cache] header to the next blank line":
:/^\[cache\]/;/^$/# 11 [cache]
12 host = redis.internal
13 port = 6379
14 ttl = 300
15Note the ; between the two addresses. With ;, Vim moves to the first address before
working out the second, so /^$/ searches from the [cache] line. With ,, both searches
start from the cursor. With the cursor on line 1, I typed the comma version:
:/^\[cache\]/,/^$/dBackwards range given, OK to swap (y/n)?The second search found the blank line after [server] (line 5), above [cache]. Swapping
would have deleted lines 5 to 11, half of the file and the wrong half. I answered n. Use
; whenever the second address is a search that should start from the first.
Offsets on patterns let you include or exclude the boundaries. Only the keys of the
[database] section, without the header or the blank line:
:/^\[database\]/+1;/^$/-1# 7 host = db-primary.internal
8 port = 5432
9 pool_size = 10Commands that work on ranges
| Command | Short | Does |
|---|---|---|
:delete [x] | :d | delete the lines (into register x if given) |
:yank [x] | :y | yank the lines |
:put [x] | :pu | put a register's text below the line (:0put for the top) |
:move {address} | :m | move the lines below {address} (0 means the top) |
:copy {address} | :t or :co | copy the lines below {address} |
:join | :j | join the lines with spaces (:j! adds no spaces) |
:> / :< | shift right / left by shiftwidth | |
:normal {keys} | :norm | run Normal-mode keys on each line |
Moving and copying: :m and :t
Moving the whole [cache] section, including its trailing blank line, so it sits above
[database]:
:/^\[cache\]/;/^$/m /^\[database\]/-1 1 ; checkout service configuration
2 [server]
3 port = 8080
4 workers = 4
5
6 [cache]
7 host = redis.internal
8 port = 6379
9 ttl = 300
10
11 [database]
12 host = db-primary.internal
13 port = 5432
14 pool_size = 10
15
16 [logging]
17 level = debug
18 format = jsonThe destination /^\[database\]/-1 is "the line before the [database] header", and :m
puts the lines below its destination. You never had to know a line number.
:t copies instead of moving. :t. duplicates the current line (like yyp without touching
any register), and :/^\[database\]/;/^$/t$ copies the database section to the end of the
file as a starting point for a replica section:
18 format = json
19 [database]
20 host = db-primary.internal
21 port = 5432
22 pool_size = 10
23Joining, shifting and deleting into a register
:3,4j 3 port = 8080 workers = 4:3,4j! joins without the space: port = 8080workers = 4. :7,9> indents the database keys
by one shiftwidth.
:d and :put with a register move text over long distances without visual selection.
Moving the [logging] section (the last three lines) to just below the comment on line 1:
:/^\[logging\]/;$d x
:1put x 1 ; checkout service configuration
2 [logging]
3 level = debug
4 format = json
5 [server]:m would have done this in one step; the register version is useful when you'll paste the
same text in several places. Registers are covered in
Macros and Registers.
:normal: Normal mode on every line
:normal takes keystrokes and runs them on each line of the range, with the cursor starting
at the beginning of the line. It turns any Normal-mode edit into a range command:
:3,4normal A ; tuned 2 [server]
3 port = 8080 ; tuned
4 workers = 4 ; tuned
5Insert mode ends by itself when the keys run out, so you don't need an Escape at the end.
Two things to know: :normal uses your mappings (:normal! ignores them, which is safer in
scripts), and it treats everything after it as keys, including |, so it can't be followed
by another command on the same line. That second point bites in
Macros and Registers when combining :normal with
:argdo.
:global: run a command on every matching line
:[range]g/pattern/command:global (:g) first marks every line in the range (the whole file by default) that matches
the pattern, then runs the command on each marked line. :v (or :g!) does the same for
lines that don't match. The command defaults to :p (print), which makes :g a grep
inside Vim. These examples use an application log:
2026-11-09 10:42:01 INFO [http] GET /api/cart 200 12ms
2026-11-09 10:42:01 DEBUG [db] pool size=10 idle=7
2026-11-09 10:42:02 INFO [http] GET /api/products 200 48ms
2026-11-09 10:42:03 WARN [cache] redis latency 220ms
2026-11-09 10:42:03 DEBUG [db] query took 3ms
2026-11-09 10:42:05 ERROR [payment] provider timeout after 30000ms order=88412
2026-11-09 10:42:05 INFO [http] POST /api/checkout 502 30011ms
2026-11-09 10:42:06 DEBUG [db] pool size=10 idle=6
2026-11-09 10:42:09 ERROR [payment] provider timeout after 30000ms order=88415
2026-11-09 10:42:09 INFO [http] POST /api/checkout 502 30004ms
2026-11-09 10:42:10 WARN [cache] redis latency 310ms
2026-11-09 10:42:12 INFO [http] GET /api/cart 200 9ms
2026-11-09 10:42:14 ERROR [db] deadlock detected on table orders
2026-11-09 10:42:15 DEBUG [db] retrying transactionListing and counting
:g/ERROR/# 6 2026-11-09 10:42:05 ERROR [payment] provider timeout after 30000ms order=88412
9 2026-11-09 10:42:09 ERROR [payment] provider timeout after 30000ms order=88415
13 2026-11-09 10:42:14 ERROR [db] deadlock detected on table ordersTo count without listing, use the n flag of :s, which reports matches and changes nothing:
:%s/ERROR//gn3 matches on 3 linesDeleting matching or non-matching lines
The two most common uses. Remove the debug noise:
:g/DEBUG/d2026-11-09 10:42:01 INFO [http] GET /api/cart 200 12ms
2026-11-09 10:42:02 INFO [http] GET /api/products 200 48ms
2026-11-09 10:42:03 WARN [cache] redis latency 220ms
[…]
2026-11-09 10:42:14 ERROR [db] deadlock detected on table ordersTen lines remain, none of them DEBUG. Or keep only the problems, deleting every line that matches neither ERROR nor WARN:
:v/ERROR\|WARN/d2026-11-09 10:42:03 WARN [cache] redis latency 220ms
2026-11-09 10:42:05 ERROR [payment] provider timeout after 30000ms order=88412
2026-11-09 10:42:09 ERROR [payment] provider timeout after 30000ms order=88415
2026-11-09 10:42:10 WARN [cache] redis latency 310ms
2026-11-09 10:42:14 ERROR [db] deadlock detected on table ordersMoving and copying matching lines
:g/ERROR/t$ copies each error to the end of the file, in order, leaving the original lines
in place. The last three lines afterwards:
2026-11-09 10:42:05 ERROR [payment] provider timeout after 30000ms order=88412
2026-11-09 10:42:09 ERROR [payment] provider timeout after 30000ms order=88415
2026-11-09 10:42:14 ERROR [db] deadlock detected on table orders:g/ERROR/m0 looks similar but moves each match to the top one after another, so each move
lands above the previous one and the order reverses. The first three lines:
2026-11-09 10:42:14 ERROR [db] deadlock detected on table orders
2026-11-09 10:42:09 ERROR [payment] provider timeout after 30000ms order=88415
2026-11-09 10:42:05 ERROR [payment] provider timeout after 30000ms order=88412Taken to its logical end, :g/^/m0 matches every line and reverses the whole file, a classic
trick that replaces tac.
Running :s and :normal on matches
Any Ex command works after the pattern. :normal is the most flexible, because it brings all
of Normal mode with it. Flag the errors for a handover note:
:g/ERROR/normal A <-- page on-call2026-11-09 10:42:05 ERROR [payment] provider timeout after 30000ms order=88412 <-- page on-call
2026-11-09 10:42:09 ERROR [payment] provider timeout after 30000ms order=88415 <-- page on-call
2026-11-09 10:42:14 ERROR [db] deadlock detected on table orders <-- page on-call:s inside :g limits a substitution to matching lines, which is often easier than one
complicated pattern. Putting a space before ms, only on [http] lines:
:g/\[http\]/s/ \(\d\+\)ms$/ \1 ms/2026-11-09 10:42:01 INFO [http] GET /api/cart 200 12 ms(First line shown; every [http] line changed the same way, and the [cache] lines, which
also end in ms, did not.)
:sort and its options
:sort sorts the range (the whole file by default) and has options for the cases plain
alphabetical order gets wrong.
| Command | Sorts |
|---|---|
:sort | by byte value: B before a, 10 before 2 |
:sort! | reversed |
:sort i | ignoring case |
:sort n | by the first decimal number in each line |
:sort u | and removes duplicate lines (combine: :sort ui, :sort nu) |
:sort x / :sort f | by hexadecimal / floating-point number |
:sort /pat/ | by what comes after the match of pat |
:sort /pat/ r | by the match of pat itself |
Text order versus numeric order:
retries=10
retries=2
retries=33
retries=1:sort gives 1, 10, 2, 33; :sort n gives 1, 2, 10, 33; :sort! n gives
33, 10, 2, 1.
The pattern forms solve "sort by this column". These hosts need ordering by the last octet of the IP:
10.20.1.110 api-03
10.20.1.12 web-02
10.20.1.9 web-01
10.20.1.101 api-01:sort n changed nothing here, because the first number on every line is 10. Skipping past
the first three octets fixes that:
:sort /\d\+\.\d\+\.\d\+\./ n10.20.1.9 web-01
10.20.1.12 web-02
10.20.1.101 api-01
10.20.1.110 api-03With r, the match is the sort key instead. Keeping only the [http] lines and sorting them
by response time:
:v/\[http\]/d
:sort /\d\+ms$/ r n2026-11-09 10:42:12 INFO [http] GET /api/cart 200 9ms
2026-11-09 10:42:01 INFO [http] GET /api/cart 200 12ms
2026-11-09 10:42:02 INFO [http] GET /api/products 200 48ms
2026-11-09 10:42:09 INFO [http] POST /api/checkout 502 30004ms
2026-11-09 10:42:05 INFO [http] POST /api/checkout 502 30011ms"The first number in the line" is literal, and it bit me with metric names. Sorting
p99=1.25, p99=0.8, p99=12.5 with :sort f left them in their original order, because
the first number on every line is the 99 in p99. Sorting on what follows the = works:
:sort /=/ fp99=0.8
p99=1.25
p99=12.5:sort x has the same trap in an even sneakier form: on id=0x1f, the d in id is a
valid hex digit. :sort /=/ x sorted 0xa, 0x1f, 0x100 correctly.
:sort u keeps the first of each set of identical lines. Duplicates that differ only in case
survive unless you add i. On web-02, web-01, web-02, Web-03, web-01, :sort u gave
Web-03, web-01, web-02: the capital W sorts before every lowercase letter.
Filtering through shell commands
Vim can hand lines to any program and use its output. That gives you jq, column, uniq,
awk and the rest of the toolbox from
Searching and Filtering Text without leaving the editor.
| Command | Does |
|---|---|
:{range}!cmd | replace the lines with the output of cmd, which reads them on stdin |
!{motion}cmd | the same, from Normal mode, for the lines a motion covers |
:r !cmd | insert the output of cmd below the cursor |
:w !cmd | send the lines to cmd as input; the buffer doesn't change |
:!cmd | just run cmd and show its output |
Pretty-printing minified JSON from an API response:
{"service":"checkout","replicas":3,"ports":[8080,9090],"env":{"LOG_LEVEL":"info"}}:%!jq .{
"service": "checkout",
"replicas": 3,
"ports": [
8080,
9090
],
"env": {
"LOG_LEVEL": "info"
}
}If the command fails, its error message replaces your text; u brings the text back.
From Normal mode, ! is an operator. In a dependency file, I put the cursor on the first
package under [runtime] and typed !ip. Vim switched to the command line and filled in the
range for the paragraph:
:.,.+3!Typing sort and Enter sorted just that block:
[runtime]
boto3
flask
requests
[dev]
pytest
blackThe [runtime] header is part of the paragraph and stayed on top only because [ sorts
before lowercase letters. Keep that in mind when you filter blocks with headers.
:r !cmd reads command output into the file, for example a date into release notes:
:r !date +\%F# Release notes
2026-11-09The backslash before % is not optional; see Common mistakes. :w !cmd goes the other way.
:w !wc -l counts the buffer's lines (14 for the log) without saving anything, and
:w !python3 runs the buffer as a script without writing a file first:
total = sum([12, 48, 9])
print(f"avg response: {total/3:.1f} ms")avg response: 23.0 ms:.!sh executes the current line as a shell command and replaces it with the output, which
is handy for generating content in place. On a line containing
echo "built on $(uname -s) with $(bash --version | head -1 | cut -d" " -f4)", it produced:
built on Linux with 5.2.21(1)-releaseWhere you'll use this
Cleaning a log for an incident report. From the 14-line log, produce a count of distinct errors with the noisy parts (order IDs) normalised:
:v/ERROR/d
:%s/.*\(\[\w\+\]\) \(.*\)/\1 \2/
:%s/order=\d\+/order=N/
:sort
:%!uniq -c
:sort! n 2 [payment] provider timeout after 30000ms order=N
1 [db] deadlock detected on table ordersLine by line: keep only errors; cut everything before the [component] tag; replace the order
numbers so identical errors become identical lines; sort so duplicates are adjacent; count
them with uniq -c; sort by the count, highest first. On a real log with thousands of lines
the commands are exactly the same.
Reordering and tidying config sections. The :m example earlier moved a section by name.
Sorting the keys inside every section is a :global with a pattern range, run from each
header:
:g/^\[/+1;/^$/-1sortThat works for every section followed by a blank line. The last section needs care; see Common mistakes.
Bulk-editing a list of hosts. An Ansible inventory maintained by hand:
# fleet inventory - edited by hand
[web]
web-01
web-02
web-03 # decommissioned 2026-10
web-04
[db]
db-01
db-02 # decommissioned 2026-09
db-03Remove decommissioned hosts, add the domain, then add a connection variable to every host line (lines that are not headers, comments or blank):
:g/decommissioned/d
:g/^[a-z]\+-\d\+$/s/$/.prod.internal/
:v/^\[\|^#\|^$/normal A ansible_user=deploy# fleet inventory - edited by hand
[web]
web-01.prod.internal ansible_user=deploy
web-02.prod.internal ansible_user=deploy
web-04.prod.internal ansible_user=deploy
[db]
db-01.prod.internal ansible_user=deploy
db-03.prod.internal ansible_user=deployCommon mistakes
% in a shell command becomes the file name
On the command line, Vim expands % to the current file name before running a shell command.
In notes.md, I first typed the command without the backslash:
:r !date +%F# Release notes
notes.mdFdate received +notes.mdF and printed it back. Escape it as \% (and # as \#, which
expands to the alternate file). The expansion is useful on purpose too: :!shellcheck %
checks the file you're editing.
:w!cmd writes a file called cmd
:w !sort (with a space) sends the buffer to sort. Without the space, ! means "force":
:w!sort"sort" [New] 18L, 224B writtenI now had a copy of the config named sort in the directory. Always put a space before the
! of a shell command.
The last section's range wraps around
The section-sorting command from above, on a file whose last section has no blank line after it:
:g/^\[/+1;/^$/-1sortE16: Invalid range: +1;/^$/-1sortand the status line said search hit BOTTOM, continuing at TOP. For [logging], there is
no blank line below, so the search wrapped around to the top of the file and produced a range
that ends before it starts. The other sections were sorted; [logging] was not. Two fixes:
make sure every section ends with a blank line (:$put _ adds one at the end, :$d removes
it afterwards), or :set nowrapscan so the search fails instead of wrapping. With the extra
blank line, [logging] came out as format = json then level = debug.
<Esc> in :normal is typed literally
:3normal A;<Esc> 3 port = 8080;<Esc>:normal reads its argument as literal characters, so <Esc> is five characters of text.
You rarely need it, because Insert mode ends when the keys run out. When you do need a special
key in the middle, build the keys with :execute and a double-quoted string, where \<Esc>
is converted to a real Escape:
:3
:execute "normal A;\<Esc>0gUiw" 3 PORT = 8080;Backwards ranges
:5,2dBackwards range given, OK to swap (y/n)?With literal numbers the swap is harmless. With pattern ranges it usually means the second
search went somewhere unexpected (the , versus ; problem from earlier). Answer n and
check the range with :# first.
Summary
- Ex commands take a range: numbers,
.,$,%, marks,'<,'>,/pattern/, with+nand-noffsets. Print a range with:#before changing it. - Separate pattern addresses with
;so the second search starts at the first match;,searches from the cursor and can give backwards ranges. :d,:m,:t(copy),:j,:>and:normalwork on any range;:mand:ttake a destination address, and0means "above line 1".:g/pat/cmdrunscmdon matching lines,:v/pat/cmdon the rest.:g/x/d,:v/x/d,:g/x/t$and:g/x/normal …cover most daily needs;:g/x/m0reverses order.:sortoptions:nnumeric,uunique,iignore case,!reverse,/pat/sort by what follows the match,rsort by the match itself.:{range}!cmdfilters lines through a program,:r !cmdinserts output,:w !cmdsends text to a program. Escape%and#in shell commands, and keep the space in:w !cmd.
Exercises
Create the app.ini and app.log files from this article to practise on.
With the cursor on line 1 of app.ini, print only the keys of the [database] section with
their line numbers, using patterns instead of line numbers.
Show Solution
:/^\[database\]/+1;/^$/-1# 7 host = db-primary.internal
8 port = 5432
9 pool_size = 10+1 skips the header, ; makes the second search start there, and -1 stops before the
blank line.
Reduce this redis.conf to just its settings. Note the indented comment.
# Redis configuration for the checkout cache
# See https://redis.io/docs/management/config/
bind 0.0.0.0
port 6379
# memory
maxmemory 512mb
# eviction policy
maxmemory-policy allkeys-lruShow Solution
:g/^\s*\(#\|$\)/dbind 0.0.0.0
port 6379
maxmemory 512mb
maxmemory-policy allkeys-lru^\s* allows leading whitespace, then the group matches either a # or the end of the line,
which catches blank lines and lines containing only spaces.
In app.log, delete every line except [http] requests that took 1000 ms or more.
Show Solution
:v/\[http\].* \d\{4,}ms$/d2026-11-09 10:42:05 INFO [http] POST /api/checkout 502 30011ms
2026-11-09 10:42:09 INFO [http] POST /api/checkout 502 30004ms\d\{4,} means four or more digits, so 1000 ms and up. :v deletes everything that doesn't
match, which here includes the [cache] lines that also end in ms.
Sort these lines by host name (the second column), not by IP address:
10.20.1.21 api-01.prod.internal
10.20.2.5 db-primary.prod.internal
10.20.1.11 web-01.prod.internal
10.20.3.7 cache-01.prod.internalShow Solution
:sort /\S\+\s\+/10.20.1.21 api-01.prod.internal
10.20.3.7 cache-01.prod.internal
10.20.2.5 db-primary.prod.internal
10.20.1.11 web-01.prod.internalThe pattern matches the IP and the spaces after it; :sort compares what comes after the
match, which is the host name.
At the top of app.ini, add a commented list of its section headers, in file order:
; [server]
; [database]
; [cache]
; [logging]
; checkout service configuration
[server]Hint
:g/^\[/t0 gets you most of the way, but look carefully at the order it produces.
Show Solution
:g/^\[/t0
:1,4g/^/m0
:1,4s/^/; /After the first command, the top of the file reads [logging], [cache], [database],
[server]: each copy went to the top, above the previous one, so the order reversed. The
second command reverses lines 1 to 4 back (the :g/^/m0 trick applied to a range), and the
third comments them. The first six lines are then exactly as shown above.
Tested with: Vim 9.1 (Ubuntu 24.04 package 9.1.0016) on Ubuntu 24.04 (WSL2), November 2026,
started as vim -u DEFAULTS, with jq 1.7, GNU coreutils and Python 3 for the filters. The
line listings came from running each command in vim -es and printing with :# or :p;
messages and prompts (E16, the backwards-range question, :w!sort) were captured from Vim
running in a terminal under tmux. Both mistakes with % and :w!sort happened to me while
preparing the examples.
Written by The Dark Debugger
Engineer documenting the things that took me too long to learn, so they take you less time. Every Vim tutorial here is tested end to end before publishing.