c:\@Work\Perl\monks>perl -wMstrict -e "my @lines = ( qq{.024. 3# keep this one \n}, qq{.024. 3# \n}, qq{.024. 3# keep this two \n}, qq{.024. 3#|a9780750247092|xisbn13\n}, qq{.024. 3# keep this three \n}, qq{.024. 3#|a0750247096|xisbn\n}, qq{.024. 3# keep this four \n}, ); print for @lines; print qq{\n}; ;; my $rx_first = qr{ [.] 024 [.] }xms; my $replace = '.020.'; ;; LINE: for my $line (@lines) { next LINE if $line =~ m{ \A $rx_first \s+ 3[#] [ ]{2} \Z }xms; $line =~ s{ \A $rx_first (?= .* [|]xisbn (?: 13)? \Z) } {$replace}xms; print $line; } " .024. 3# keep this one .024. 3# .024. 3# keep this two .024. 3#|a9780750247092|xisbn13 .024. 3# keep this three .024. 3#|a0750247096|xisbn .024. 3# keep this four .024. 3# keep this one .024. 3# keep this two .020. 3#|a9780750247092|xisbn13 .024. 3# keep this three .020. 3#|a0750247096|xisbn .024. 3# keep this four