Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Perl (http://www.go4expert.com/forums/perl/)
-   -   Perl Program to replace first 3 charaacters of a word in a file (http://www.go4expert.com/forums/perl-program-replace-3-charaacters-word-t14261/)

rag84dec 29Sep2008 14:43

Perl Program to replace first 3 charaacters of a word in a file
 
Hi all,
I have a file with some words starting with "RR_"... i want to change it to "TT_"...

For example.... a word in the file "test.txt" ... is "RR_Word"...i want it to be converted into "TT_Word"... There are 1000 such words in the file.
I am new to perl so please some one give me any idea??

oogabooga 29Sep2008 20:34

Re: Perl Program to replace first 3 charaacters of a word in a file
 
Here it is with line-by-line processing, saving to a different output file:
Code:

open IN, "<test.txt";  # input file
open OUT, ">test2.txt"; # output file

while( <IN> ) {      # read a line from IN into $_
    s/\bRR_/TT_/g;    # global substitute on $_
                        # (\b means word boundary)
    print OUT $_;    # write $_ to OUT
}

close IN;              # close files
close OUT;

If the file is not too big you can change it in place using file-slurping mode:
Code:

undef $/;              # enable file-slurping mode
open IN, "<test.txt";
$str = <IN>;          # slurp in whole file
close IN;
$str =~ s/\bRR_/TT_/g; # substitute
open OUT, ">test.txt";
print OUT $str;        # write whole file
close OUT;


ungalnanban 19Feb2010 12:47

Re: Perl Program to replace first 3 charaacters of a word in a file
 
Through command line itself we can achieve your requirement.

Code:

$perl -p -i.bak -e "s/RR_/TT_/g;"  test.txt
The -i option give the backup file.
After executing the command you will have the both files "test.txt" and "test.txt.bak" [ RR_WORLD and TT_WORLD ]


:cuss:


All times are GMT +5.5. The time now is 09:43.