How to replace a string in an existing file in Perl?

前端 未结 4 1929
迷失自我
迷失自我 2020-12-02 13:04

I want to replace word \"blue\" to \"red\" in all text files named as 1_classification.dat, 2_classification.dat and so on. I want to edit the same file so I tried this code

相关标签:
4条回答
  • 2020-12-02 13:22

    None of the existing answers here has provided a complete example of how to do this from within a script (not a one-liner). Here is what I did:

    rename($file, $file.'.bak');
    open(IN, '<'.$file.'.bak') or die $!;
    open(OUT, '>'.$file) or die $!;
    while(<IN>)
    {
        $_ =~ s/blue/red/g;
        print OUT $_;
    }
    close(IN);
    close(OUT);
    
    0 讨论(0)
  • 2020-12-02 13:23

    It can be done using a single line:

    perl -pi.back -e 's/oldString/newString/g;' inputFileName
    

    Pay attention that oldString is processed as a Regular Expression.
    In case the string contains any of {}[]()^$.|*+? (The special characters for Regular Expression syntax) make sure to escape them unless you want it to be processed as a regular expression.
    Escaping it is done by \, so \[.

    0 讨论(0)
  • 2020-12-02 13:36

    $_='~s/blue/red/g';

    Uh, what??

    Just

    s/blue/red/g;
    

    or, if you insist on using a variable (which is not necessary when using $_, but I just want to show the right syntax):

    $_ =~ s/blue/red/g;
    
    0 讨论(0)
  • 2020-12-02 13:39

    Anything wrong with a one-liner?

    $ perl -pi.bak -e 's/blue/red/g' *_classification.dat
    

    Explanation

    • -p processes, then prints <> line by line
    • -i activates in-place editing. Files are backed up using the .bak extension
    • The regex substitution acts on the implicit variable, which are the contents of the file, line-by-line
    0 讨论(0)
提交回复
热议问题