use strict; use warnings; my $string = 'Hello,World,23,,,, test,test,test test,test,test test,test,test test,test,test end,bye,,,,'; $string =~ s/((?:first line last word|last line last word),)[^\n]*/$1/g; #in your file $string =~ s/((?:23|bye),)[^\n]*/$1/g; #here in this string print $string;