Author - Web Developer - Educator
RSS Feed

VIM Search and Replace

VIMI thought I'd post this because I needed it, and quick access doesn't hurt. I had a recent experience where I needed to replace a lot of text in a text file in the command line.

While I like to use vim as my text editor of choice while in a Linux system, I hated the fact that I had to find each instance of a word and manually type out the replaced word.

So, I found a solution: (thank you VIM Wiki)

The %s command works just like wq, so you need to proceed it with a colon. But here's how it works:
I hope this seems straight forward, but here's the breakdown: %s - initiate the :substitute feature FIND - the word/phrase you want to find REPLACE - the word/phrase you want to replace it with OPTIONS - there are a series of options you can include, the most popular one being g Here is an example:
This replaces all instances of "cat" with the word "dog". Simple, right?


Here is the list of options I have come up with so far:
c - ask for confirmation (similiar to the -i flag)
i - case insensitive search/replace
I - case sensitive (the flag \C can also be tacked on to the word in case you want the word to be case sensitive only)
:%s/\<cat\>/dog/g - while not in the Options field, this searches for the whole words only (such as "cat", but not "categories")

There are plenty of other examples on the VIM Wiki page, but I thought I'd post this guide here for my benefit and anybody elses that needs it.

Tags:#vim #linux #texteditor #search #replace #guide