Read and write to the same file in Perl

Home > Search
  by

Replace text in a file

Let's say file.txt contains the text "Hello World". The following Perl script will open file.txt, and then replace the text "World" with "Earth".

# Load the content of the file into an array
open(FH, '<', '/path/to/file.txt') or die "cannot open file $! \n";
@array = <FH>;
close(FH);

# Overwrite file.txt with the content of array, while also removing and/or replacing lines
open(FH, '>', '/path/to/file.txt') or die "cannot open file $! \n";
foreach $line (@array) {
  print FH $line unless ($line m/stuff to remove/);
}
close(FH);

 


Read and write to the same file

In this example, "Hello World" is appended to the file.

my $file = "example.txt";

# Open the original file
open(IN, '<', "$file") or die "Cannot open $file $! \n";

# Create a tmp file
open(OUT, '>>', "${file}.tmp") or die "Cannot create $file.tmp $! \n";

# Append something to the top of the tmp file
print OUT "Hello Top\n";

# Copy everything in the original file to the tmp file
while (<IN>) {
  $_ =~ s/old/new/g; # Replace "old" with "new"
  print OUT $_;
}

# Append something to the bottom of the tmp file
print OUT "Hello Bottom\n";

# Close both files
close(IN);
close(OUT);

# Delete the original file
unlink($file);

# Rename the tmp file to have the original file name
rename("${file}.tmp", $file);

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments