Perl Program to replace first 3 charaacters of a word in a file

rag84dec's Avatar, Join Date: Jul 2007
Go4Expert Member
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??
0
oogabooga's Avatar
Ambitious contributor
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;
0
ungalnanban's Avatar, Join Date: Feb 2010
Go4Expert Member
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 ]