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.

[ Replace this ad for $1/month ]



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

  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 Reply, but read first

  1. Feel free to leave replies even to very old posts.
  2. Is your comment not specifically about this post?  Great!  Go here.
  3. Flame, swear, rant, shout — just don't spam!  You won't increase your PageRank, even temporarily (the URLs are tagged 'nofollow'), and I'll delete it anyway.  Save us both time.

CommentLuv badge