Strip trailing blank lines off PHP files

UNIX/Linux trick with sed:  To strip blank lines off the end of all PHP files, recursively, starting in the current directory, use this script:

find . -name '*.php' -exec sed -i -e :a -e '/^\n*$/{$d;N;ba' -e '}' '{}' \;

This edits files in place.  It changes files.  Caveat.

Credit to @Ace_NoOne at jimbojw, who in turn credits unnamed users at freenode.

6 Responses to “Strip trailing blank lines off PHP files”

Read below or add a comment...

  1. Dad says:

    Whew! 

    I’ve been wondering how to strip the blank lines off my PHP files.  Recursively, of course!  What a great sed trick.

    Thanks!  :>)

  2. mcgees.org says:

    Hey, I did my job.  To wipe the blank look off your face, you’re gonna need something like this :-) :

  3. Dad says:

    I think I’m going to need more than a line of code to understand this post of yours.  I’m not even sure the code will run in this old “386″ brain I have.

  4. mcgees.org says:

    If you’re on your phone you probably didn’t see what followed the colon in my last comment, which is a link to an Amazon page where you can buy a 432-page book teaching you how to understand this post.  As of this writing, there’s a used one for $2.99.

    The original link was a fancy iframe that your phone’s browser can’t see; to get that to work I had to do some wizardly programming.  So, beware: another post on how to do that cometh!  Some time.

  5. Dad says:

    I await with bated breath.

  6. mcgees.org says:

    Here’s a text link.  You could buy it right now!  ;-)

    Oh, and this code could work on a 386.  Theoretically.  If you could scrounge an old (really old) build of, say, Slackware.  I used one in (gulp) 1995.  Could never get it to do much useful.  But I didn’t know sed then.  :-)

Leave A Comment...

CommentLuv badge