tags:

views:

295

answers:

3

Hi,

I have a folder pulled from a wordpress installation, >1000 files. Some php code is throwing an error due to trailing spaces on the very last line (I cleaned up an iframe injection on some final lines of pages, and did find/replace with a space, but didn't know that that would throw off all my code).

What's the most efficient way to chop those spaces? I've never run a regex before, but know that's what I would use. Help!

+2  A: 

If you're certain it's a trailing space on the last line of the file, then you'd want a bash script (I'm assuming you're using Linux) to, for each file (use "find ." to get a list), tail -1 the file, and then grep that line for space or tab.

Tangentially, it's useful to know that the closing ?> is unnecessary at the end of PHP files, and it's best to omit it there. I can't count the number of times I've seen a PHP file that ends with "?> " and people go nuts trying to find that one extra space that's causing output/header problems.

dirtside
+5  A: 

Something like:

find -type f |xargs sed -i '$s/[[:space:]]+$//'

That should remove trailing spaces on the last line of any file anywhere within the cwd. The first $ is the sed address for "last line" and the second is the regex for end of line.

As always, be sure to backup first.

Matthew Flaschen
Thank you so much!
Alex Mcp
A: 

in this case what i would do is write a script or program that when given a directory it recursively goes through finding files ending in .php or whatever then simply write a function that 1)seeks to the last byte and stores this position 2)if this byte is whitespace seek back a byte and check again 3)if it is not white space return the offset

then using that you can either write out each file as a new copy or over the old one

P.S one of the above solutions would also work :P