I have done this so many times, still I find a new problem doing recursive search and replace each time! Here's one small shell script that puts the issues I had on the Mac doing search and replace on a directory recursively.
Save the file as rpl.sh, chmod it 755, and execute it like:
-
./rpl.sh folderContainingFiles/ oldText newText
Does the job for me! This could be done in a single line, I got some ideas of using xargs etc, but all that did not work on my Mac (at least). So resorting to this.
-
#!/bin/sh
-
grep -rl $2 $1 |
-
while read filename
-
do
-
(
-
echo $filename
-
sed "s/$2/$3/g;" $filename> $filename.xx
-
mv $filename.xx $filename
-
)
-
done
And yes, if you are going to use this, take a little time and do some argument checking before passing them around! Unless you think only a God user like you is going to use it!
4 comments ↓
find containingFolder/ -type f -exec sed -i~ “s/oldText/newText/g” {} \;
The exec part here: wouldn’t it fork a new process for every file? Is that a good practice? I thought otherwise!
BTW, Manish has a way to do this using Perl - http://mannu.livejournal.com/406783.html.
for i in `find` ; do sed “s/pattern/replacement/g” “$i” >> “$i.xx”; mv “$i.xx” “$i”; done
I don’t know if this work in mac.
Leave a Comment