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
Replace value in txt file with a new value
Started by summer5, Jun 23 2010 01:30 AM
2 replies to this topic
#1
Posted 23 June 2010 - 01:30 AM
|
|
|
#2
Posted 24 June 2010 - 07:49 PM
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
Posted 04 July 2010 - 05:21 PM
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 /


Sign In
Create Account

Back to top









