Mar 24, 2013

Replace string in all files in a directory in perl


We will discuss briefly about the script (To replace string in all files in a directory in perl)

Please define your directory path in the following :
my $input_dir  = "/usr/src/perl_test/input/";
my $output_dir = "/usr/src/perl_test/output/";
my $log_dir    = "/usr/src/perl_test/log/";

Define the string to replace and string to replace with as mentioned below
my $str_to_replace = "Mother Teresa":
my $str_replace_with = "MOTHER TERESA";

If you want to replace a particular string in all the files in the same directory path, then give the same path for both $input_dir & $output_dir.
E.g.,
my $input_dir  = "/usr/src/perl_test/same_path/";
my $output_dir = "/usr/src/perl_test/same_path/";

Log Directory :
It creates the log file(log_<timestamp>.log) in the path mentioned in $log_dir

Important Note : 
Please take a backup before running the script for safer side in case if you are replacing the strings in the same folder


conversion_script.pl
#!/usr/intel/bin/perl

use strict;
use warnings;
use Data::Dumper;

my $input_dir  = "/usr/src/perl_test/input/";
my $output_dir = "/usr/src/perl_test/output/";
my $log_dir    = "/usr/src/perl_test/log/";

my $str_to_replace = "Mother Teresa":
my $str_replace_with = "MOTHER TERESA";

my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst);

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
 $sec  = sprintf("%02d",$sec);
 $min  = sprintf("%02d",$min);
 $hour = sprintf("%02d",$hour);
 $mday = sprintf("%02d", $mday);
 $mon  = sprintf("%02d", $mon+1);
 $year = sprintf("%04d", $year+1900);

my $output_tag = $mday .'_'. $mon .'_'. $year .'_'. $hour .'_'. $min;

opendir(IN_DIR, $input_dir)   or die $!;
opendir(OUT_DIR, $output_dir) or die $!;
opendir(LOG_DIR, $log_dir)    or die $!;

open (LOG_FILE, "> $log_dirlog_$output_tag.log");

print LOG_FILE "------------- START ------------ \n";

#print LOG_FILE "Started Copying Files from Source: $srcdir   to Destination: $dest \n";
#my $cmd = "cp -R $srcdir/* $dest/";
#`$cmd`; #or die "Chk the command : " . $cmd;
#print LOG_FILE "Finished Copying Files from Source: $srcdir   to Destination: $dest \n";

my (%files_changed, %files_not_changed, @invalid_list_files);

while (my $file = readdir(IN_DIR)) {

    # Ignore if it is not file 
    unless (-f "$input_dir$file") {
       print LOG_FILE "-W- Not a File, Ignoring : " . $file . "\n";
       next;
    }

    print LOG_FILE "\n\nFile Name : " . $file . "\n";

    open(IN_FILE, "<$input_dir$file") || warn "Cant open file for reading: " . "$input_dir$file";
    my @lines = ;
    close(IN_FILE);

    my @newlines;
    foreach my $each_line (@lines) {
        #chomp $each_line;
        if($each_line =~ /$str_to_replace/) {
            print LOG_FILE "Converting String From : " . $each_line;
            $each_line =~ s/$str_to_replace/$str_replace_with/ig;
            print LOG_FILE "Converting String To   : " . $each_line;
            push(@newlines, $each_line);
            $files_changed{$file} = 1;
        } else {
            push(@newlines, $each_line);
            $files_not_changed{$file} = 1;
        }   
    }

    open(OUT_FILE, ">$output_dir$file") || warn "-W- Cant open file for writing: " . "$output_dir$file";
    print OUT_FILE @newlines;
    close(OUT_FILE);
}

my @f_changed     = keys %files_changed;
my @f_not_changed = keys %files_not_changed;

print LOG_FILE "\n\nOutput Summary as below ------------------------- : ";

print LOG_FILE "\n List of all the Files changed     : " . Dumper(\@f_changed);
print LOG_FILE "\n List of all the Files NOT changed : " . Dumper(\@f_not_changed);

print LOG_FILE "\n\n Total No.of files changed   : " . scalar(@f_changed);
print LOG_FILE "\n Total No.of files NOT changed : " . scalar(@f_not_changed);

close (LOG_FILE);
closedir(IN_DIR);
closedir(OUT_DIR);
closedir(LOG_DIR);

1;  


Input Directory: /usr/src/perl_test/input/
1) mother_teresa_intro.txt
Mother Teresa born on August 26, 1910
Full name of Mother Teresa is "Agnes Gonxha Bojaxhiu"
Mother Teresa founded the Missionaries of Charity, which in 2012 consisted of over 4,500 sisters and is active in 133 countries.

2) mother_teresa_awards.txt
In 1962, Mother Teresa was awarded the Ramon Magsaysay Award
In 1979, Mother Teresa was awarded the Nobel Peace Prize, for work undertaken in the struggle to overcome poverty and distress
In 1980, Mother Teresa was awarded the Bharat Ratna Prize  


Output Directory: /usr/src/perl_test/output/
1) mother_teresa_intro.txt
MOTHER TERESA born on August 26, 1910
Full name of MOTHER TERESA is "Agnes Gonxha Bojaxhiu"
MOTHER TERESA founded the Missionaries of Charity, which in 2012 consisted of over 4,500 sisters and is active in 133 countries.


2) mother_teresa_awards.txt
In 1962, MOTHER TERESA was awarded the Ramon Magsaysay Award
In 1979, MOTHER TERESA was awarded the Nobel Peace Prize, for work undertaken in the struggle to overcome poverty and distress
In 1980, MOTHER TERESA was awarded the Bharat Ratna Prize  


Log Directory: /usr/src/perl_test/log/
log_<time_stamp>.log


No comments:

Post a Comment