my $string = ""; while ( <$IN> ) ## $IN needs to be open { chomp; if ( $_ eq "END" ) { $string = join ( " ", split " ", $string ); # $string =~ s/$other//g; ## In case you need to remove other characters print $OUT "$string\n"; ## $OUT is open output file $string = ""; next; } $string .= $_; }