iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🔎

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

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.

https://github.com/ggreer/the_silver_searcher

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': Replaces old with new

Mac comes with Perl 5 pre-installed, so it's helpful as no installation is required.

https://github.com/Perl/perl5

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