Quick bash one-liner to find a rogue newlinePosted Wed, Jul 16, 2008 in:
It’s been far too long since I’ve posted, so I’m writing a short post about a quick one-line I just used to solve a problem.
The problem was a rogue newline appearing at the beginning of some generated XML files, which is against the rules for XML.
This problem, and a similar one involving data being sent before headers can be sent, often happens in PHP when an extra newline is included after the closing “?>”. One way to fix it is to just leave off the closing bit, since PHP is smart enough to realize the file has ended in PHP mode.
Anyway, we had to track down which file had this problem in it, and the solution ended up being this:
for i in `find . -name '*.php'`; do echo $i:`tail $i -n 1` | grep -v '\?>'; done
That finds each php file and checks its last line for “?>”, printing it out if it’s not there.
Of course, there will be some false positives for PHP files which have HTML after their PHP code or don’t have the closing “?>”, but it’s good enough to track down those potentially offending files.