If I understand the problem correctly you are trying to eliminate duplicate lines that match a pattern where the lines immediately follow each other.

This code will open a file called file.html and if there are two or more lines in succession that are identical and contain the text sample then the duplicates are removed and file.html is rewritten.

use IO::String; my $regex = qr/sample/; my $file = 'file.html'; open my $in , '<', $file or die "Can't open $file: $!\n"; my $new_html; my $new = IO::String->new($new_html); my $last = ''; my $modified; while ( my $line = <$in> ) { if ( $line =~ /$regex/ ) { if ($line ne $last) { print {$new} $line; } else { ++$modified; } } else { print {$new} $line; } $last = $line; } close $in; close $new; if ($modified) { rename $file, "$file.bak" or die "Can't rename $file: $!\n"; open my $out, '>', $file or die "Can't open $file: $!\n."; print {$out} $new_html or die "Can't print to $file: $!\n." }

Update: Just read shmem's rather neat answer and updated my code to make a backup if the file is modified.


In reply to Re: Regex to undo a regex? by hipowls
in thread Regex to undo a regex? by hmbscully

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.