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

前端 未结 4 1941
迷失自我
迷失自我 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()
    {
        $_ =~ s/blue/red/g;
        print OUT $_;
    }
    close(IN);
    close(OUT);
    

提交回复
热议问题