Crawlicious | tools for web business

TAG | vim

Jun/09

3

search and replace in vim

So, how do you do a search and replace in vim? There are two ways that I know of, the first is a general search and replace in the whole file, and the other is a search and replace in just a selected area.

First the general search and replace. Press escape to make sure that you are in command mode. Then type :%s/FOO/BAR/ and hit enter, to replace all FOOs with BARs in the whole file. Note, this will only modify the first occurrence in each line. To modify every occurrence in each line, simply follow the ending slash with a g, like this :%s/FOO/BAR/g . Now, what if the search or replacement has a ‘/’ in it? You can use another character as your search delimiter, the key is that you must be consistent, like this :%s#FOO#BAR#g is equivalent to the above search and replace command.

To do a search and replace in selected text, first, select some text. For our example, lets grab 3 lines, so press escape just to be sure that you are in command mode, then type V, that will select the current line, then go down (press j or down arrow) and now type : . Lets just pause here and look at the vim command prompt, it now looks weird, like this ‘<,'> . But that is ok, now you can just do the s/FOO/BAR/g command and hit enter. You should have changed all FOOs to BARs, but only in your selected area. YAY! It works!

Hide

Find it!

Theme Design by devolux.org