Append newline to files



I need to go through few hundred text files and append newline for
files that don't end with newline. So I have the following code to
read the file:

local $/ = undef;
open(handle, $filename) || die($!);
$content = <handle>;
close(handle);

Then use the following to check:

if($content =~ m/.*\n$/)
{
# file end with newline, do nothing
}
else
{
open(handle, ">>", $filename) || die($!);
print handle "\n";
close(handle);
}

The above code is working fine but I noticed some of the files have LF
as newline (probably originated from Unix) while the others are CRLF
(Windows). The perl script will run on a Windows machine with
ActiveState Perl 5.6, and \n is always CRLF when written to file.

Is there a way to tell Perl to append LF for Unix files and CRLF for
Windows files?

Or do I have to specifically look for \x0d\x0a and then append \x0d or
\x0d\x0a accordingly?
.



Relevant Pages

  • Re: Append newline to files
    ... that don't end with newline. ... as newline while the others are CRLF ... The perl script will run on a Windows machine with ... ActiveState Perl 5.6, and \n is always CRLF when written to file. ...
    (comp.lang.perl.misc)
  • Re: Deleting blank lines
    ... > newline is just the end of line character, it's not a blank line (if I ... I'm trying to help someone edit some files from the command line, ... He has been struggling with all kinds of commands to append email addresses ... Then he can use the script when necessary to append to the files. ...
    (comp.unix.shell)
  • Re: [9fans] acme g/$/ funny
    ... shouldn't this append "foo" after every line? ... every empty line. ... not the newline itself. ...
    (comp.os.plan9)
  • Re: How to append a file accordingly?
    ... If he wants to append, ... normalizing newlines see PerlIO::eol. ... when the $lastchars are just normal characters. ... Note that text files *should* end with a trailing newline (in the ...
    (comp.lang.perl.misc)
  • Re: Editing files with File::Find
    ... > My main question is this: Since both versions of &wanted modify the ... But if you can use the append method (which is much simpler and ... what happens if your program or machine crashes in ... Would you want to just append another newline ...
    (comp.lang.perl.misc)