[Chicago-talk] folding multiple newlines at eof
Steven Lembark
lembark at wrkhors.com
Tue Aug 16 10:19:37 PDT 2005
-- Jason Perkins <jperkins at sneer.org>
> I'm attempting to convert runs of multiple newlines at the end of
> files into a single newline. The following one liner is converting
> all runs of newlines throughout the file to a single newline:
>
> find . -name '*.php' -exec perl -00 -pi -e 's/\n{2,}$/\n/s' {} \;
>
> Can anyone suggest a means of correcting the behaviour? Explanations
> with your fix even more greatly appreciated so that I can figure this
> out on my own next time.
slurp the file and zap the newlines at EOL:
#!/path/to/perl -p
BEGIN { undef $/ };
s/\n+\Z//;
or, if you prefer
{
local $/;
my $string = <$ARGV>;
$string =~ s{ \n+ \Z}{}x;
print $string;
}
(someone else'll have to remember what use English
does to $/... :-).
Both ^ and $ are designed to apply mutlple times within
a string and locate themselves based on embedded newlines.
The \A and \Z meta char's are zero-width and only apply
at the start and end of the entire string. By anchoring
a search for newlines at the end-of-string (vs. end-of-
line) you'll strip only the trailing newlines.
Damian suggests in PBP using only \A and \Z, dropping
^ and $ entirely, becuase people make the mis-assumption
about EOL and EOS too frequently.
--
Steven Lembark 85-09 90th Street
Workhorse Computing Woodhaven, NY 11421
lembark at wrkhors.com 1 888 359 3508
More information about the Chicago-talk
mailing list