Sunday, December 7, 2008

vi vim gvim find search replace string on multiple files

Method 1: For replacing single file

'''''''''''' start run1.bat ''''''''''
@echo off

:: FileName
SET fileName="test.html"

:: Search and Replace
vim -S replace1.vim %fileName%

echo Done!
PAUSE
'''''''''''' end run1.bat ''''''''''

'''''''''''' start replace1.vim ''''''''''
:set nobackup
:%s/Windows/Linux/g
:wq
'''''''''''' end replace1.vim ''''''''''


Method 2: For replacing multiple Files, specify the filename in vim command line.

'''''''''''' start run2.bat ''''''''''
@echo off

:: Search and Replace
vim -S replace2.vim *.html
:: Or
vim -S replace2.vim test1.html test2.html test3.html

echo Done!
PAUSE
'''''''''''' end run2.bat ''''''''''

'''''''''''' start replace2.vim ''''''''''
:set nobackup
:argdo! %s/Windows/Linux/g | update
:wq
'''''''''''' end replace2.vim ''''''''''


Method 3: For replacing Multiple Files, specify the filename list using args and argdo.

'''''''''''' start run3.bat ''''''''''
@echo off

:: Search and Replace
vim -S replace2.vim

echo Done!
PAUSE
'''''''''''' end run3.bat ''''''''''

'''''''''''' start replace3.vim ''''''''''
:set nobackup
:args *.html
:argdo! %s/Windows/Linux/g | update
:wq
' Note: The ":argdo" command takes an argument that is another command.
' That command will be executed on all files in the argument list.
'''''''''''' end replace3.vim ''''''''''



Comments:
See :args and :argdo

How to use :args to search recursive in subdirectories?

you can use something like this:

:args *.cpp */*.cpp */*/*.cpp

Not exactly recursive, but works well for reasonably flat directory hierarchies
http://vim.wikia.com/wiki/Run_find/replace/search_on_multiple_files_and_subdirectories

No comments: