Search and Replace in Multiple Files


We learned how to search and replace within a single file, this tip discussed how to extend that capability to multiple files.

As a first step, let's define the pattern and replacements text we want to execute on a single file:

Initial Conditions
a·=·[
····"one",
····"two",
····"three",
····"five",
]
COMMANDTop1:1
:%s/five/four/n

As a simple example, let's change all occurrences of five to four. The command to do this is:

:%s/five/four

Let's test it on one file to be sure it works. We will add the n flag so that we can see the results but not execute the changes themselves:

Test the Pattern
a·=·[
····"one",
····"two",
····"three",
····"five",
]
NORMALTop1:1
1 match on 1 line

OK, that looks correct. Now that we have built the command we want to run, the next step is to define the list of files over which we will execute this command. This is done using the :args command. Suppose we want to execute this command over all python files in the current working directory. We can populate those paths in the arglist using:

:args ./*.py

we can verify the paths that we inserted into the arglist using:

:args

Now that the arglist has been populated, we can execute our command on each of the files in the list by calling :argdo and passing our search and replace command from above as an argument:

:argdo %s/five/four
Execute the Command
a·=·[
····"one",
····"two",
····"three",
····"four",
]
NORMAL71%5:5