Being able to search and replace text, regardless of how it is stored is a humoungous time saver so I thought I'd share a couple methods I use.
SSH BASH perl one line search replace
I usually do my file editing & programming work via SSH with PuTTY so a command line search and replace is really handy especially when large amount of files are involved. Here is an example of altering one file . . .
perl -pi -e "s/old text/new text/gi;" filename.txt
Remove the g to only replace the 1st occurrence of old text. Remove the i to make it case sensitive.
Of course replacing the example filename "filename.txt" with files you actually need to alter, for example, change all mentions of oldsite to newsite in all .php files in the current directory
perl -pi -e "s/oldsite/newsitet/gi;" *.php
Or, to do every php file even ones in sub directories...
perl -p -i -e 's/oldsite/newsite/g' `find ./ -name *.php`
Of course perl and BASH being what they are, there are likely 30 different ways to do th same thing, but thus far this one has worked just fine. It is also incredibly fast
What I recommend is copy the files you plan to do search replaces on to a new temporary directory, and test your search replace commands to ensure they have no undesired consequences.
MySQL query to search replace.
Often I need to quickly and accurately change text in a MySQL database. Here is a MySQL query that does exactly that.
update [table_name] set [field_name] = replace([field_name],'[string_to_find]','[string_to_replace]');
Using PHPMyAdmin it is pretty easy to make a copy of the table and use it for test runs of search replace queries. Depending on the application a search replace done incorrectly could spell disaster so never ever do search replaces on a live and in use mysql table.
As an example, I wind up moving a lot of Wordpress websites in my freelance work, typically from my own development area on my webserver, to the new account my client has created for their live Wordpress site. This MySQL query can be modified for your use when moving a Wordpress site.
update wp_options set `option_value`
= replace(`option_value`,
'URL TO MY WORDPRESS DEV',
'URL TO THE LIVE WORDPRESS SITE');
Other methods.
While I live in a SSH shell most of my computing day I am on a Windows workstation. and occasionally do need to search replace text files on my own hard drive. Thus far I don't have an elegant solution but using Windows file search, with the content search option I can get a nice tidy list of files that need the edit. I can then select as many as I need (or as many as my computer can handle) and right click to open with Notepad++ . From there I can do a search replace on all open documents and save them in a couple of clicks.
Software mentioned in the article
PuTTY : http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html
Notepad ++ : http://notepad-plus.sourceforge.net/
Saturday, February 27, 2010
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment