Global search and replace using the command line
23
Dec
Tags: totally cool stuff || 1 Comment
If you have ever used Dreamweaver, you are probably familiar with the Global Search and Replace feature, which allows you to search and replace amongst all files with in a site, which can be very handy if you are doing a static site. If you are too hard core for Dreamweaver though, and you spend your whole day buried in a terminal window, how can you achieve the same thing? By this piece of bash-trickery, that’s how:
find . | grep html | xargs -t -I {} sh -c "cat {} | sed 's/Stuff to find/Replace with this/' > {}"
- find . - find all the files from the current directory down
- grep html - filters the output to include only filesnames with html in them
- xargs -t -I {} sh -c - pumps the file names into the cat command, but also sets a variable called {} that holds the filename
- sed ’s/Stuff to find/Replace with this/’ - just a search and replace
- > {} - save the output back to the original file name
A word of warning though, leave the last bit off until you are sure your output is correct, because there is no undo feature

