Recursive Global Search and Replace in Linux
// June 6th, 2011 // No Comments » // Adventures in File Sitting
I was working on a very old project of mine, a MUD called DooMMUD (based off of the popular id Software series of games) and just for shits n giggles, I thought I would move the codebase over to something newer and more stable like the Circle-based tbaMUD codebase just to see if I could get it up and running again.
At some point I needed to change some Variables and Classes (structs really) over the entire codebase (e.g. coins to credits)
No way was I going to bother editing all the files (if I could even find them all), I would almost definitely miss something.
So I used a combination of grep and xargs & sed to recursively go through every directory in the tbaMUD structure and replace every string or replace every phrase that I needed changed.
Behold the majesty of my one line command:
grep -rl matchstring somedir/ | xargs sed -i 's/string1/string2/g'
We pipe the recursive results from grep into xargs & sed which takes those results and run a global search and replace within each instance of string1 with string2.
Huzzah!
I remember when I was 8 years old, my father had made me an account on his Sun Microsystem Workstation 3/80 running some later version of SunOS. I used KornShell over a matter of person preference (I don’t think BASH was even around back then) and every day I would look into /usr/bin or /bin to look for new command, run man page on it and tinker around with it.
My father said it best when he said “Its like having a Christmas Present every single day”. The man was right.



