abaugher@bannor:~/work/perl/monks$ cat 939472.pl #!/usr/bin/perl use Modern::Perl; open my $in, '<', '939472.txt' or die $!; my $n = 0; # current number while(my $line = <$in>){ chomp $line; # capture any digits directly following 'name' # and the text following the first space my( $nn, $text ) = $line =~ /name(\d+)\S*\s+(.+)$/; if( $nn == $n ){ # already working on this name? print " $text"; # if so, then print what we've got } else { # if not, start a new line print "\n" unless $n == 0; # unless this is the first line print "name$nn $text"; # print the new number and text $n = $nn; # and update the name counter } } print "\n"; abaugher@bannor:~/work/perl/monks$ cat 939472.txt name1 TOM RAT name1.1 AND name1.1.1 JERRY name2 BAT MAN name2.1 CAN name2.1.1 FLY name2.1.2 ANYWHERE abaugher@bannor:~/work/perl/monks$ perl 939472.pl name1 TOM RAT AND JERRY name2 BAT MAN CAN FLY ANYWHERE