#!/usr/bin/perl use strict; use warnings; #SSCCE: my %mycorpus = ( text1 => "This is line 1 from text 1 another line here which should be included in the text file with the above line. This is line 2 from text 1 This is line 3 from text 1", text2 => "This is line 1 from text 2 This is line 2 from text 2 another line here which should be included in the text file with the above line. This is line 3 from text 2", ); my $count = 1; foreach my $filename (sort keys %mycorpus) { for ( $mycorpus{$filename} =~ /This is(?:(?!This is).)*/sg ) { my $outputname = 'UserA_' . $count++ . '.txt'; open my $outfile, '>', $outputname or die "$! opening $outputname"; print $outfile "$_\n"; # \n only if desired close $outfile; } } # for testing file contents system "more UserA* | cat";