karan
karan

Reputation: 33

how to apply gvim regular expressions to multiple files

How to apply regular expressions to multiple files in gvim ?

Upvotes: 1

Views: 740

Answers (2)

Peter Rincker
Peter Rincker

Reputation: 45087

I am going to assume "apply regular expressions", means use a substitution via :s over many files.

Vim does not come with an "all-in-one" native project-wide find & replace command. Instead it is typically a two step process:

  • Collect locations/files/buffers/windows/tabs
  • Apply a command over the collection with a *do command

Arg list

The arg list is simply a list of files. You can populate it when you start Vim, e.g. vim *.txt or via :args once Vim has started.

:args *.txt
:argdo %s/foo/bar/g | w

Quickfix/Location List

The quickfix (& location list) are simply a list of locations, e.g. file, line, column. You can populate these lists with many commands, e.g. :vimgrep, :grep, :make, :cexpr, etc. Use :cdo to run a command over each location. :cfdo will run a command over each file in the list.

:vimgrep /foo/ **/*.txt
:cfdo %s/foo/bar/g | w

Many people like to use :grep as you can customize the 'grepprg' to use a fast grep alternative, e.g The Silver Searcher, ripgrep, ack. I would also recommend mapping :cnext & :cprev.

Buffers

You can run a command on all opened buffers with :bufdo. Use :ls to see what buffers you have open.

:bufdo %s/foo/bar/g | w

Windows

Can run a command over all windows in a the current tab page with :windo. This is helpful to do diff'ing via :windo diffthis.

:windo %s/foo/bar/g | w

Tabs

Run a command over all tabs via :tabdo.

:tabdo %s/foo/bar/g | w

Assorted tips

Some thoughts for better find & replace workflows.

  • Use the e flag to prevent :s from stopping when no match can be found.
  • May want to build your search pattern ahead of time then use :s//{replacment} to avoid typing out the pattern again.
  • Look into using traces.vim to give a visual feedback for substitutions.
  • As with all project-wide substitutions it is best to use some sort of version control (e.g. git, mercurial, svn) in case something goes terribly wrong.

Personally, I typically use quickfix list for most of my multiple file substitutions. I use :grep with ripgrep for fast project searching.

For more help see:

Related Vimcasts episodes:

Also see:

:h :s
:h :bar
:h arglist
:h :argdo
:h quickfix
:h :cdo
:h :grep
:h :vimgrep
:h 'grepprg'
:h buffer
:h :bufdo
:h window
:h :windo
:h tabpage
:h :tabdo

Upvotes: 6

keerthan kumar
keerthan kumar

Reputation: 393

try opening all files in tab mode i.e gvim -p file1 file2 .....

then do :tabdo

Upvotes: 2

Related Questions