Walker News

How To Do Interactive Search And Replace Using Vi Editor?

It’s pretty fast and easy to have Vi automatically search and replace all existence of a target word in text file, if you’re confident with your regular expression (e.g no error).

For example, this command :1,%s/the/WALKER/g effectively replace any words containing “the” to “WALKER”, e.g. “the”, “other”, “these”, etc.
Obviously, the regular expression is not correct, if your intention is to replace the exact word. In this case, it should be this:

  • 1,% means from first to last line, i.e. all lines in the edited file. So, to perform on 3rd to 5th line, write it as 3,5.
  • s/\<the\>/WALKER/ means search exact word “the” and replace it with “WALKER”,
  • g means all occurrence of the search text found in each line. Without this “g” command, “s” only find and replace the first occurrence found in each line.

So, would be great if it’s possible to get Vi editor confirms text replacement with you for each the target text it found in text file (e.g. source code)?

Using Vi editor to perform search and replace interactively

Just use “c” command (short for confirmation). For example:

You’ll see it prompts replace with WALKER (y/n/a/q/l/^E/^Y)?, where
  • y for yes
  • n for no
  • a for all (as if “c” option is not used)
  • q for quit
  • l for last (i.e. quit after replace this)
  • ^E and ^Y indicate CTTL+E and CTRL+Y respectively for scrolling text. Seriously, I don’t know how to use these two CTRL keys :(

Custom Search

2014  •  Privacy Policy