Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 36 ยท Projects and Practice

Project: Refactor Text with Macros and :cdo

A hands-on Vim project: clean a messy CSV and a code base using :g, :v, :normal, :s, recorded macros and :cdo, with a stand-in engine that lets you test each transformation.

Real editing jobs are rarely one command. You clean data, rename things across files, reshape lines, and verify the result. This project walks through three realistic jobs and teaches how to choose the right tool: an Ex command for patterns, a macro for irregular steps, :cdo for many files.

A reminder: Vim is not available on this page. The commands are shown as the real editor behaves, and the runnable blocks are JavaScript stand-ins that perform the same transformation so you can check the idea and compare your expected result.

Choosing the tool

Which tool?

:s and :g Same change, a pattern finds it
Macro Several steps per item
:cdo / :argdo Many files

Try the simplest tool that expresses the change.

1 / 2

Job 1: clean a messy CSV with Ex commands

Suppose people.csv looks like this:

TEXT
name, age ,city
 Ann,31 , Oslo
bob,28,  oslo

Carl ,45,Rome
# test row
dora,,Rome

Goals: remove blank lines and comments, trim spaces around every field, capitalize names, drop rows with a missing age.

VIM
:g/^$/d                      " delete blank lines
:g/^#/d                      " delete comment lines
:%s/\s*,\s*/,/g              " trim spaces around commas
:%s/^\s\+\|\s\+$//g          " trim line ends
:%s/^\(\w\)/\u\1/            " capitalize the first letter of each line
:v/,\d\+,/d                  " delete every line that does NOT contain ,digits,

Why this works:

  • :g/pattern/cmd runs cmd on every line that matches; :v/pattern/cmd (or :g!) on every line that does not.
  • \u in the replacement uppercases the next character; \L...\E lowercases a stretch.
  • :g is one undoable change, so u returns the file to its state before the whole command.
  • The header row name,age,city is deleted by the last command because it has no digits; protect it with a range: :2,$v/,\d\+,/d.

Order matters: do the blank-line cleaning first so later patterns do not need to handle empty lines.

JS Stand-in: run the CSV clean-up steps

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Job 2: reshape lines with :normal and a macro

A list of function names needs to become a numbered list of calls:

TEXT
load
parse
render

Target:

TEXT
1. load();
2. parse();
3. render();

With :normal: run keystrokes on a range.

VIM
:%normal A();
:%s/^/\=line('.') . '. '/

:%normal A(); plays A(); (append) on every line; the second line uses \= to put an expression in the replacement: the current line number.

With a macro: record once and replay. Place the cursor on line 1 and:

TEXT
qa            start recording into register a
0             go to the start of the line
i1. <Esc>     (type the number by hand for the first line)
A();<Esc>     append the call
j             move down
q             stop recording
2@a           replay twice
@@            repeat the last macro

Macros are better when each item needs a different action; because the number here changes, the expression version is cleaner. A good macro rule: start by moving to a known position (0) and end by moving to the next item (j), so it chains. Add a count (50@a), and it stops at the first failing motion, such as j on the last line, which is a handy built-in stop condition.

The macros chapter covers recursive macros and editing a macro as text with "ap and "ayy.

JS Stand-in: what :%normal A(); and the numbering do

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Job 3: rename across a code base

You rename the function fetchUser to loadUser in a project.

VIM
:args **/*.js
:argdo %s/\<fetchUser\>/loadUser/ge | update

or search first and review in the quickfix list (see the quickfix lesson):

VIM
:vimgrep /\<fetchUser\>/j **/*.js
:copen
:cfdo %s/\<fetchUser\>/loadUser/ge | update

:cfdo runs once per file that had a match. Use :cdo s/.../.../ | update for per-match control, for instance when only calls with a particular argument should change. For a project-wide rename of a symbol in a language with a language server, prefer vim.lsp.buf.rename (grn in Neovim), because it understands scope, as the LSP lesson explains.

Verify: :vimgrep /fetchUser/ **/*.js should now report no matches, and git diff shows exactly what changed. Commit before the run so you can revert with git restore . if the pattern was too broad.

JS Stand-in: word-boundary rename across files

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Habits that make refactoring safe

  1. Commit first; refactor in a clean working tree.
  2. Test the pattern with /pattern and :%s/pattern//gn (the n flag only counts matches).
  3. Prefer \<word\> boundaries and the very-magic flag \v for readability.
  4. Run it on one file before running it on all.
  5. Use :cdo for per-match control and :cfdo for per-file commands.
  6. Check with git diff and run your tests.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which command deletes every line that does NOT contain a digit?

    :v is the inverse of :g, so :v/\d/d deletes lines that lack a digit.
  2. 2. What does :%normal A(); do?

    :normal executes keys as normal-mode commands; with a range it runs on each line.
  3. 3. Why does a macro with a count stop by itself at the end of a file?

    When a command in a macro fails, the rest of the repeats are cancelled.
  4. 4. Which command runs a substitution once per file that has a quickfix entry?

    :cfdo visits each file in the quickfix list once; :cdo visits every entry.

Summary

  • Use :g and :v with Ex commands for pattern-based line work; they undo in one step.
  • Use :normal for ranges of simple key sequences and macros for multi-step, per-item edits.
  • Use :argdo, :cdo and :cfdo for many files, adding | update.
  • Commit first, test patterns with the n flag, and verify with git diff.

Next: Practice: Vim Golf Challenges