iTranslated by AI
Find and Replace Text Across Multiple Files in a Directory
Conclusion
Bulk replace files under a directory by searching for a keyword
ag -l 'keyword' | xargs perl -pi -e 's/old/new/g'
Explanation
Keyword Search
Use full-text search.
ag -l 'keyword'
The -l option displays only the filenames that match. By default, it displays the lines in the files where the keyword is found.
I use The Silver Searcher, but you could use something else as well.
Execute replacement for each file
Pass the output of ag (filenames) as arguments to perl using xargs, and execute the replacement with perl.
xargs perl -pi -e 's/old/new/g':
-
-p: Processes each line and prints the result -
-i: Edits the file in place -
-e: Executes Perl code -
's/old/new/g': Replacesoldwithnew
Mac comes with Perl 5 pre-installed, so it's helpful as no installation is required.
perl --version
This is perl 5, version 34, subversion 1 (v5.34.1) built for darwin-thread-multi-2level
...
Afterword
If it's a single file, you can just use :%s/old/new/g in Vim or something similar, but it's tedious when there are many files, so this script was meant for doing it in bulk.
When making changes, it's a good idea to check the targets that will be changed using The Silver Searcher first.
ag 'keyword'
Discussion