As someone with a lot of Python experience, I normally try to stay away from Perl. However, I have really been impressed with its ability to work easily with regex and its integration with pipes/redirection for quick work on the CLI.

Normally, you can easily use Sed to find and replace text in a file with something like the following:

$ sed -i 's/SEARCH_FOR/REPLACE_WITH/g' file.txt

"One file? My Files have files!"

I get you. You could use a combination of find and xargs but honestly I find it to be a bit confusing. Instead this is when I like to break a handy perl one liner:

$ perl -pi -w -e 's/SEARCH_FOR/REPLACE_WITH/g;' *.txt

Options explained

-p:   Places a printing loop around your command so that it acts on each
      line of standard input. Used mostly so Perl can beat the
      pants off awk in terms of power AND simplicity
-i:   Modifies your input file in-place (making a backup of the
      original). Handy to modify files without the {copy,
      delete-original, rename} process.
-e:   Allows you to provide the program as an argument rather
      than in a file. You don't want to have to create a script
      file for every little Perl one-liner.
-w:   Activates some warnings. Any good Perl coder will use this.

You can use any separator/delimiter you want

For example, this would also be valid:

$ perl -pi -w -e 's|HELLO|BYE|g;' test.txt

A Truly recursive find and replace that ignores git repos

The one problem with the above Perl command though is that it does not handle recursing down folders.

For that, I usually break out the following command:

find . -not -path '*/\.git*' -type f -exec sed -i 's/search_text/replace_text/g' {} +

Comments

comments powered by Disqus