I am trying to write a perl script that will read a file line by line, compare a specific substring of each line with a line of a previously read line, and if it is different, write it to a new file. In essence, the script removes the unique lines among consecutive lines of the file.
The script seems to suffer from a logical error, because instead of getting unique lines in the output file, I just get the ending line.
use strict; my $src='/var/www/pinginfo/ugvps'; my $tar="target"; open(INP, $src) or die("Could not open: $!."); open(OUTP, ">", $tar) or die "Couldn't open: $!"; my $lastrd=""; while( my $line = <INP> ) { if ( &IsSame($lastrd, $line)) { print "Unique line: ".$line."\n"; print OUTP $line; $lastrd=$line; } else { print "Line was the same: ".$line."\n"; } } print OUTP "Done"; close (OUTP); close (INP); exit 0; sub IsSame { my $old=$_[0]; my $new=$_[1]; if ( $old == "" ) { return 0; } my @values_old = split('\|',$old); my @values_new = split('\|',$new); if ( $values_old[3] eq $values_new[3] ) {
The file "target" after execution contains a single line Done .
My source file is as follows:
UGVPS|6.6.6.6|03-08-2013 10:16:21 PM|0 UGVPS|6.6.6.6|03-08-2013 11:06:01 PM|0 UGVPS|6.6.6.6|03-08-2013 11:08:01 PM|100 UGVPS|6.6.6.6|03-08-2013 11:10:01 PM|0 UGVPS|6.6.6.6|03-08-2013 11:14:01 PM|100 UGVPS|6.6.6.6|03-08-2013 11:16:01 PM|0 UGVPS|6.6.6.6|03-08-2013 11:52:02 PM|0 UGVPS|6.6.6.6|03-08-2013 11:54:01 PM|100 UGVPS|6.6.6.6|03-08-2013 11:56:01 PM|100 UGVPS|6.6.6.6|03-08-2013 11:58:01 PM|100 UGVPS|6.6.6.6|04-08-2013 12:00:01 AM|0 UGVPS|6.6.6.6|04-08-2013 12:02:01 AM|100 UGVPS|6.6.6.6|04-08-2013 12:04:01 AM|100 UGVPS|6.6.6.6|04-08-2013 12:06:01 AM|100 UGVPS|6.6.6.6|04-08-2013 12:08:01 AM|100 UGVPS|6.6.6.6|04-08-2013 12:10:01 AM|100 UGVPS|6.6.6.6|04-08-2013 12:12:01 AM|100 UGVPS|6.6.6.6|04-08-2013 12:14:01 AM|100 UGVPS|6.6.6.6|04-08-2013 12:16:01 AM|100 UGVPS|6.6.6.6|04-08-2013 12:18:01 AM|100 UGVPS|6.6.6.6|04-08-2013 12:20:01 AM|100 UGVPS|6.6.6.6|04-08-2013 12:22:01 AM|100 UGVPS|6.6.6.6|04-08-2013 12:24:01 AM|0 UGVPS|6.6.6.6|04-08-2013 02:38:01 AM|0
source share