One of the main frustrations most vim users has could be doing find and replace operations across multiple files, from within vim.
I will list down few techniques with some use cases.
Use case one: Find and replace a dependency version in multiple package.json files in a monorepo.
Imagine you have a monorepo containing multiple Node.js packages, each with its own package.json file. You want to update the dependency version of "foo" from v3.5 to v4.0 in all package.json files. To achieve this, you can use the following command:
:args ./**/*package.json
:argdo %s/foo-v3.5/foo-v4.0/
The args
command sets the argument list to the specified files, and the subsequent argdo
command runs on each file in the argument list. The argdo %s/foo-v3.5/foo-v4.0/
command performs a global search and replaces within the current file, replacing "foo-v3.5" with "foo-v4.0".
This technique is useful when you know all the files that need modification beforehand, as it can be more efficient than the technique used in the next use case.
Use case two: find and replace a term any term in multiple files
Suppose you want to replace all occurrences of "foo" with "bar" in all TypeScript files under the "./src" directory.
:grep foo ./src/**.ts
:cdo %s/foo/bar
The grep
command searches for the specified pattern in the specified files and outputs a list of matching lines. The subsequent cdo
command operates on each line in the list and runs the following %s/foo/bar
command. This performs a global search and replace within the current file, replacing "foo" with "bar".
This technique is useful when you don't know all the files that need modification beforehand or when you want to apply changes to specific lines or patterns within files.
In addition to these techniques, Vim offers many more powerful commands for working with multiple files simultaneously. By mastering these commands, you can greatly enhance your productivity as a Vim user.