Find And Replace Strings

Posted by: admin  :  Category: Perl, Shells

Imagine you have a directory with thousands of text files, each of which containing some keywords to be replaced.

While there’s a lot of tools out there allowing you to find and replace strings in text files, there’s always a goog reason to use the tools that you already have.

The following snippet uses find in combination with perl to achieve the task:

#find /my/path -type f -exec perl -i -p -e ‘s/search/replace/g;’ {} \;

This command line instructs to find all files within /my/path, passing them to perl, which is instructed to find and replace given strings instantly.

Rememver however that this is not binary safe so you should run this only on directories containt text files.

The get additional verbosity add the ‘-print’ flag to find’s command line to see which files is being worked on.

If you pass an optional extension to ‘-i’ (eg. ‘-i.bak’) perl is instructed to create a backup by the same filename plus extension.

As always: man find and man perl are your friends.


Comments are closed.