develooper Front page | perl.beginners | Postings from February 2009

Add Line break when first of a line changes

Thread Next
From:
Jack Butchie
Date:
February 15, 2009 05:25
Subject:
Add Line break when first of a line changes
Message ID:
000901c98f70$ddb6bea0$400110ac@cooldaddio
I have a txt file of products that I would like to be able to insert a blank 
line whenever the name of the product changes, to make it easier to read.  I 
found this srcipt hunting about but I don't know how to apply it to the text 
file. I've tried all kinds of different things but just don't get it.



example of text file named: products.txt

LAWN SEED    34.00    RED
LAWN SEED1    36.00    BLUE
LAWN SEED1    36.00    BLUE
LAWN SEED1    36.00    BLUE
LAWN SEED2    37.00    PINK

 #!/usr/bin/perl -w

 my $file = shift @ARGV;

 open IN, $file or die "Couldn't open $file: $!";
 my $before_line;
 while (my $new_line = <IN>) {
  print "\n" if ( $before_line and $before_line ne $new_line );
  print $new_line;
  $before_line = $new_line;
 }

 close IN;


Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About