DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Search And Replace Over File(s) With Perl

02.21.2006
| 24792 views |
  • submit to reddit
        A quick bit of Perl can come in handy if you have an old site to update that has no CMS, or something similar.

To change 'source' to 'destination' in all HTML files in the current directory:

perl -pi -e 's/source/destination/g' *.html

You could use this to update copyright notices, etc.. but bear in mind you need to stay with Perl/regex syntax, so escape those forward slashes, etc :)    

Comments

Snippets Manager replied on Tue, 2007/01/23 - 5:15pm

On FreeBSD -i option should be used with the backup postfix: sed -i.bak -e 's/source/destination/g' *.html Plus '\r','\n','\t' will not work in some versions of sed, so be carefull, using perl regex mostly secure. '*.html' can be replaced with the 'find' command to ensure that it will works on different systems: find /where/to/start/search -name '*.php' -type f -exec perl -pi -e 's/source/destination/g' {} \; If you want to see which files was modified: find /where/to/start/search -name '*.php' -type f -exec perl -pi -e 's/source/destination/g' {} \; -print [Qualiteam.biz] Alexander Driantsov

Snippets Manager replied on Mon, 2012/05/07 - 2:20pm

I've only used sed once or twice and forgot about its applicability here. Thanks!

Snippets Manager replied on Mon, 2006/02/20 - 8:08pm

For what it's worth, this regex behaviour possible using the unix "sed" command, without having to start up a perl interpreter. For most simple tasks, this is better, but if you had some complex processing to do, then using perl would make sense. sed -i -e 's/source/destination/g' *.html Add -r if you need extended regexp in sed.

Snippets Manager replied on Mon, 2006/02/20 - 8:08pm

For what it's worth, this regex behaviour possible using the unix "sed" command, without having to start up a perl interpreter. For most simple tasks, this is better, but if you had some complex processing to do, then using perl would make sense. sed -i -e 's/source/destination/g' *.html Add -r if you need extended regexp in sed.