#!/usr/bin/perl -w use strict; undef $/; my $all; while () { open F, $_ or die "Can't open $_: $!\n"; my $content = ; close F; $all .= "Name: $_\n$content"; if ($content =~ /\b(\w+\d\d\d)\b/) { my $found = $1; (my $first_two) = $content =~ m/(^[^\n]*\n[^\n]*\n)/; print "Found $found\n$first_two\n"; } } open F, ">res.txt" or die "Can't write res.txt $!\n"; print F $all; close F;