Append newline to files

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
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>;

Then use the following to check:

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

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?

Re: Append newline to files

On Mon, 28 Jul 2008 17:41:41 -0700, p19010101 wrote:

Quoted text here. Click to load it

The latter. And what are you going to with a file without any newlines?

1) Better s/0x0d//g, make all the files the same format.

2) Or investigate if it are only the Windows files missing a trailing
lineseparator, it's a typical Windows problem.


Re: Append newline to files

Quoted text here. Click to load it

And here you just fell into the trap.

If "\n" is a line _seperator_, then a trailing line separator would
simply indicate another emtpy line at the end of the file:
would contains 3 lines, 'foo', 'bar' and an empty line.

If on the other hand "\n" is a line _terminator_ then the above string
would contain 2 lines. And
would still be only two lines with some trailing junk.


Re: Append newline to files

On Tue, 29 Jul 2008 20:14:01 +0000, J├╝rgen Exner wrote:

Quoted text here. Click to load it

You're right. But on Windows, it's a line separator[1]. On Unix, it's a
line terminator. So there is no correct way.


[1] Although many programs follow Unix conventions, so it's ill advised
to rely on this.

Site Timeline