1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

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

Discussion in 'Perl' started by rag84dec, Sep 29, 2008.

  1. rag84dec

    rag84dec New Member

    Joined:
    Jul 17, 2007
    Messages:
    49
    Likes Received:
    0
    Trophy Points:
    0
    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??
     
  2. oogabooga

    oogabooga New Member

    Joined:
    Jan 9, 2008
    Messages:
    115
    Likes Received:
    11
    Trophy Points:
    0
    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;
    
     
  3. ungalnanban

    ungalnanban New Member

    Joined:
    Feb 19, 2010
    Messages:
    45
    Likes Received:
    2
    Trophy Points:
    0
    Location:
    Chennai
    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:
     

Share This Page