The equivalent-opposite Perl code to chomp
is s/^\n//
. Instead of doing it on the last line (eof), do it on the first line. Even though it will only be an empty line, removing the newline will mean that line will print nothing in the output.
perl -pe 's/^\n// if $. == 1' filename >filename2
or in place:
perl -pi -e 's/^\n// if $. == 1' filename
Since starting newlines are by definition empty lines, you can also just skip printing them by using -n
instead of -p
(same behavior but without printing, so you can determine which lines to print).
perl -ni -e 'print unless $. == 1 and m/^\n/' filename
If you want to remove potentially multiple starting newlines, you could take another approach; advance the handle yourself in the beginning until you receive a non-empty line.
perl -pi -e 'if ($. == 1) { $_ = <> while m/^\n/ }' filename
It's all much easier if you don't mind reading the entire file into memory at once rather than line by line:
perl -0777 -pi -e 's/^\n+//' filename
To avoid doing any excess work editing the file unless it starts with newline characters, you could condition the edit by prefixing it with another command (reads first line of the file and causes a non-zero exit status if it doesn't start with a newline):
perl -e 'exit 1 unless <> =~ m/^\n/' filename && perl ...