Search-replace recursively in files and folders

Jun 18, '10 07:30:00AM

Contributed by: locojohn

I wrote a bash script that lets you search and replace text strings in files of a specified folder and its subfolders recursively. Key features:

One of the main reasons for me to write this script compared to existing alternatives was a possibility to implement simulation mode (fake replacement demonstration mode) combined with presenting clear results, in order to quickly distinguish between searched and replaced text.

In simulation mode (switch -s) no actual replacements will be performed, but you can see what is being replaced (with ANSI color diff output, if colors are supported by your terminal; even work with pipes). By utilising 'while read file' loop it is possible to see results coming at once with no delay, so long as there are matched strings found -- makes perfect sense for a long tree of folders and sub-folders -- no waiting time until script finishes.

[crarko adds: The author mailed me an updated version of the script; please download it at the link given below.]

Some examples of usage:

Replace 'blue' with 'green' in all files in the current directory tree. No actual replacement is done because of the '-s' switch (run in simulation mode)

srpl -s . 'blue' 'green'

Delete leading whitespace (spaces, tabs) from front of each line -- aligns all text flush left.

srpl 's/^[ \t]*//'

Tested on Mac OS X 10.6.3, Linux Slackware 8.1, 10.1 and Gentoo 2.0.1.

[crarko adds: I haven't tested this one. The script's source is available at here, along with that of another script by the same author. I left out some additional examples of using the script to recursively edit PHP source files, but it looks like a useful tool in that area.]

Comments (8)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20100601024851474