On Unix, I want to ensure all program files in my $DEV directory are correctly terminated with a newline (most will be correct). I want the solution to be fast and short (in that order).

Any solution must properly handle file names with spaces in them (GNU find/xargs can use -print0/xargs -0, but standard find/xargs requires you to escape spaces with \ to stop xargs choking). Two attempts follow. The xargs solution seems a little faster than the pure Perl one. Improvements welcome.

#!/bin/sh find "$DEV" -name '*.cpp' -o -name '*.h' -o -name '*.c' | \ perl -lne'sysopen(Z,$_,0) && sysseek(Z,-1,2) && sysread(Z,$c,1) && clo +se(Z) or warn("$_: $!\n"),next;$c eq "\n" or s/ /\\ /g,print' | \ xargs perl -i -lpe'eof && warn "Fixed $ARGV\n"'
#!/bin/sh perl -MFile::Find -le'find({no_chdir=>1, wanted=>sub{/\.c(?:pp)?$/||/\ +.h$/ or return;sysopen(Z,$_,0) && sysseek(Z,-1,2) && sysread(Z,$c,1) +&& close(Z) or warn("$_: $!\n"),return;$c eq "\n" or push@f,$_}},$ENV +{DEV});@f||exit;@ARGV=@f;$^I="";while(<>){chomp;print;eof && warn "Fi +xed $ARGV\n"}'

In reply to Properly newline terminate a bunch of files on Unix by eyepopslikeamosquito

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.