Wednesday, September 29, 2010

Replace a string in a file and rewrite to the same file.

Perl One liner:

% perl -pi -e 's/HEAD/TAIL/g' file


Using sed command:

% sed 's/PERL/perl/g' txt1 > TMP_FILE

% mv TMP_FILE txt1
Using Perl Script: 
#!/depot/perl-5.8.3/bin/perl

open FH1,"txt1";
@arr1=<FH1>;
open FH1,">txt1";
foreach $l (@arr1){
$l =~ s/this is sarala/this is SARALA/g;
print FH1 "$l";
}
close FH1;


(or)
 #!/depot/perl-5.8.3/bin/perl

open FH1,"txt1";
@arr1=<FH1>;
foreach my $l (@arr1) {
$l =~ s/this is sarala/this is SARALA/g;
##print "$l";
}
print "@arr1";
close FH1;
unlink txt1;
open FH2, ">", "txt1";
print FH2 "@arr1";
close FH2;



No comments:

Post a Comment