s/\s*$/\n/s; # assuming \s will catch your newline s/\s*[\r\n]+$/\n/; # otherwise, this should do it