Hind Forsum
Hind Forsum

Reputation: 10507

vim: How to search/replace in all opened files?

If I use :vimgrep, it searches all files under current directory. But my requirement is to search/replace among all opened files.

E.g. I'm using vim to open 3 files at the same time

vim 1.cpp 2.cpp 3.cpp

I wish to:

  1. search all functions called "main" and display in quickfix window, among all 3 files.

  2. Replace all "hello" with "world" in all 3 files.

Upvotes: 11

Views: 9157

Answers (5)

Ziyadsk
Ziyadsk

Reputation: 479

Use the command :

bufdo %s/string/replacement/g 

bufdo : action on all buffers .
s : replacing
g : globally .

Upvotes: 17

YaOzI
YaOzI

Reputation: 17478

According to the way you work with multiple files in vim (tabs, windows, etc), you can search and replace in multiple files by using different command:

  • :tabdo (all tabs)
  • :windo (all windows in the current tab)
  • :bufdo (all buffers, i.e. all those listed with the :ls command)
  • :argdo (all files in argument list)
  • :cdo (all files listed in the quickfix list)

First open multiple files with vim tab pages:

$ vim -p file1.txt file2.txt

then in the vim, you can search and replace in multiple files by using:

:tabdo %s/pattern/replace/gc

Upvotes: 6

Milan Parmar
Milan Parmar

Reputation: 130

i have used the following command which works for me. use this command sequential.

:set autowriteall :bufdo! %s/pattern/replace/g

Upvotes: 3

romainl
romainl

Reputation: 196586

If your Vim is recent enough you can use the :cdo command:

:vimgrep main {1,2,3}.cpp
:cwindow
:cdo s/foo/bar/g

Upvotes: 6

user7435588
user7435588

Reputation: 13

You can use the command mode. %s/(findstring)/(replacestring)

Upvotes: -3

Related Questions