Jump to content

Replace value in txt file with a new value

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
summer5

summer5

    Newbie

  • Members
  • Pip
  • 4 posts
hi all,

I had write a user-defined value to a txt file using perl script in windows7.

But when come to load a new user-define value to the txt file,I face problem as it write the new value in next line. What I want is the new value will replace the former value in txt file.

I'm new to perl,can someone help me in this problem? It will be very good if you can shows me some perl script as example and reference.

Thanks,
Summer

#2
tate

tate

    Learning Programmer

  • Members
  • PipPipPip
  • 90 posts
you can do something like renaming the original file, copying the contents into a new file except change the one line you want to be different and then remove the original file. so something like this:
rename("filename","filename-1");
open(FILE,"<","the renamed filename") or die("error reading file.");
open(OUTFILE,">","filename") or die("error");
while(<FILE>){
    my $line=$_;
    chomp($line); #removes \n from line.
    if($line eq "the line you want to change"){
        print OUTFILE "Whatever you want to change that line to in the file";
    }else{
        print OUTFILE "$line\n";
    }
}
close(FILE);
close(OUTFILE);
unlink("filename-1");
exit;

twas brillig

#3
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,722 posts
Woah, dude...overkill there. I can't test this right now (my Ubuntu partition is shot to hell at the moment), but I'm pretty sure this'll work.

my $inp;
open($inp, "+<myfile.txt") or die "File open error: $!\n";

my ($i, $thisline);
while( !eof($inp) ) {
    $thisline = <$inp>;
    if( $thisline eq $DESIRED_LINE_CONTENT ) {
        print $inp $NEW_LINE_CONTENT;
        last;
    }
}

sudo rm -rf /