perl -ne 'if(/(\w+\.csv)/){close $fh if defined $fh;open $fh,">$1"} elsif(/([0-9.-]+)/){print $fh "$1\n"}' file.txt #### open FILE, " ) { # read a line if ( /(\w+\.csv)/ ) { # If the line is a filename... close $fh if defined $fh; # close previous open $fh,">$1"; # and open new for writing } elsif ( /([0-9.-]+)/ ) { # If the line is a number... print $fh "$1\n"; # write it } } close $fh; # close the files opened close FILE;