Linux: How do I mass find and replace text in files under linux using perl?

Few friends have asked me how to do mass find and replace text in files under linux. There are quite a bit of options in linux to achieve mass replacing of text in files. If you are doing it file by file, you can achieve that in vi by opening, running replace and closing and going to next file. But sometimes that can be very tedious and you would rather do mass replacement on all files containing certain extension. We can do this by using sed or perl. Since most people are familiar with perl (at least most system admins and programmers), I will show you a perl way of doing it which you can use with sed as well if you wish. First step is to get perl to do what we want on one file

perl -w -i -p -e "s/search_text/replace_text/g" filename

-w turns warnings on
-i makes Perl operate on files in-place (if you would like to make backups, use -i.bak, this will save filename.bak files)
-p loops over the whole input
-e specifies Perl expression
filename works on one file at a time

Once we get the results we want, we can now pass it multiple files by doing something like:

perl -w -i -p -e "s/search_text/replace_text/g" *.php

This will search and replace within all php files in the directory you are in.

Now, let us say you want to go through your whole web directory and replace every place where you have “Perl is good” to “Perl is great”, you would use following command:

find /www_root -name "*.php"|xargs perl -w -i -p -e "s/Perl is good/perl is great/g"

find will start at /www_root, look for filenames which have .php extension, xargs takes that filename and passes it to perl as an arguement.

DISCLAIMER: Please be smart and use code found on internet carefully. Make backups often. And yeah.. last but not least.. I am not responsible for any damage caused by this posting. Use at your own risk.

408 thoughts on “Linux: How do I mass find and replace text in files under linux using perl?

  1. billionaire psychic

    Hi! Quick question that’s entirely off topic. Do
    you know how to make your site mobile friendly?
    My web site looks weird when browsing from my iphone.
    I’m trying to find a template or plugin that might be able to resolve this problem.

    If you have any recommendations, please share. Thanks!

  2. bitcoincasino

    Your writing is perfect and complete. bitcoincasino However, I think it will be more wonderful if your post includes additional topics that I am thinking of. I have a lot of posts on my site similar to your topic. Would you like to visit once?

  3. gacor24

    It’s actually very complicated in this active life to listen news on Television, so
    I simply use internet for that purpose, and obtain the latest news.

Leave a Reply

Your email address will not be published. Required fields are marked *