Something quick and dirty for tonight? Try Perl pie

If you ever need to replace any text or emails in a flat file but don’t want to go through the whole file looking for what you want to replace, you can try out Perl pie.

Here’s the situation, your boss asks you to test out a bunch of scripts with tons of emails in them. For testing purpose, you want the emails to go yourself. It would be extremely painful to go through each file and replace each email. And of course, you can do “sed” command to replace the emails, but “sed” command is a ready-only command, it doesn’t actually modify the files. What you can do here is to use Perl pie and it will replace everything it finds and replace it. Here’s how it works:

Suppose you want to replace all emails to your email, You could do this,

perl -pi -e ‘s/\$?\w+\.?\w+\@\w+.\w+/sam\’ filename

Now all the email addresses in “filename” will be replaced with And if you understand regular expression, you will know what my pattern is looking for. Of course, my regex (regular expression) is not proven to match every kind of email address, but it should match most of the emails. To understand what I did there, I will have to explain the syntax.

perl -pi -e ‘s/find_regex/replacement/g’ filename

Note that you should do this with care because once you execute this command, there’s no rollback. Therefore you should create a backup copy of the file you trying to replacement. To learn more about regex, I will be creating videos on them. You will appreciate how powerful regex can be and how Perl has set a standard for regex.

I hope this helps and that you will use Perl pie more often from now on. If you are still confused, no worry, I will be creating a video on Perl pie as well. This weekend I will be starting to record videos on UNIX, so stay tuned.

Feel free to drop a comment