Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
714 views
in Technique[技术] by (71.8m points)

How do I replace a line in a file using Perl?

How do I change the contents of a file from this:

setenv api1000 Delhi
setenv CODEDROP regular
setenv RELEASETYPE build
setenv CDBUILD CD30

To this (replaced string regular to CD29 in second line)

setenv api1000 Delhi
setenv CODEDROP CD29
setenv RELEASETYPE build
setenv CDBUILD CD30

my attempt:

my $CD_VER = CD29;

open RF, "<$OldFile" or die "Cannot open $OldFile for reading.";
open WF, ">$NewFile" or die "Cannot open $NewFile for writing.";

while ( <RF> ) {
    if (/CODEDROP/){
        if( /regular/) {
            $_ =~ s/regular/$CD_VER/ ;
            print WF "$_";      
        }
    }

close RF;
close WF;

copy("$NewFile","$OldFile");  # both became same

OUTPUT I am getting as below in destination file:

setenv api1000 Delhi
setenv CODEDROP regular   ( I NEED  to REMOVE this LINE )
setenv CODEDROP CD29       ( only this line should be there )
setenv RELEASETYPE build
setenv CDBUILD CD30
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The only actual problem with your code was that you were printing the line to the new file in the wrong place in the loop. You need to print every line from the old file into the new file.

Having tidied your file a little and updated some of the idioms, I end up with this:

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

my $old_file = 'in.txt';
my $new_file = 'out.txt';

my $CD_VER = 'CD29';

open my $rf, '<', $old_file or die "Cannot open $old_file for reading.";
open my $wf, '>'. $new_file or die "Cannot open $new_file for writing.";

while ( <$rf> ) {
    if (/CODEDROP/ and /regular/) {
        s/regular/$CD_VER/ ;
    }
    print $wf $_;
}

close $rf;
close $wf;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...