• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 239
  • Last Modified:

How to edit some lines of an existing file in Perl?

Hi,
This is the code I tried to use to open and edit some matching lines of an existing file. But it looks like, it does not work.

Can you please let me know what I am doing wrong?

open my $TEMPFILE, "+<$file" 
                      or die "Couldn't open temp file: $! \n Check if the temp file is created.";	
					  
	while (<$TEMPFILE>){
		s{ \w+ , \s \w+ \s+ \d+ , \s 20\d\d \s+ \d\d : \d\d : \d\d }{Weekday, Month DD, 20YY  HH:MM:SS}xmsg;
		s{ / 20 \d\d \d\d \d\d _  \d\d \d\d }{/20YYMMDD_HHMM}xmsg;
		s{href="(file://///).*?(/20YYMMDD_HHMM)}{$1***$2};	
	}
	
close $TEMPFILE;
}

Open in new window



Thanks,
0
Tolgar
Asked:
Tolgar
2 Solutions
 
arober11Commented:
Short answer: You can't directly, see: http://perldoc.perl.org/perlopentut.html#Mixing-Reads-and-Writes

Solution: either write each read and / or manipulated line to a temporary file, then truncare and rename the files at the end, alternatively call sed.
0
 
FishMongerCommented:
You could edit the file by using: Tie::File - Access the lines of a disk file via a Perl array

[Edit]
To be more specific, this is what I'm suggesting.
tie my @tempfile, 'Tie::File', $file or die "failed to tie '$file' $!";

foreach ( @tempfile ) {
    s{ \w+ , \s \w+ \s+ \d+ , \s 20\d\d \s+ \d\d : \d\d : \d\d }{Weekday, Month DD, 20YY  HH:MM:SS}xmsg;
    s{ / 20 \d\d \d\d \d\d _  \d\d \d\d }{/20YYMMDD_HHMM}xmsg;
    s{href="(file://///).*?(/20YYMMDD_HHMM)}{$1***$2};	
}
untie @tempfile;

Open in new window

0
 
ozoCommented:
# or
{local @ARGV=($file); local $^I=".bak";

      while ( <> ){
            s{ \w+ , \s \w+ \s+ \d+ , \s 20\d\d \s+ \d\d : \d\d : \d\d }{Weekday, Month DD, 20YY  HH:MM:SS}xmsg;
            s{ / 20 \d\d \d\d \d\d _  \d\d \d\d }{/20YYMMDD_HHMM}xmsg;
            s{href="(file://///).*?(/20YYMMDD_HHMM)}{$1***$2};      
                print;
      }      
}
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now