Remove closing PHP tags from all files

Viewed 181

I am trying to find and remove all the closing PHP tags ?> from the end of the PHP files on a website.

I have used:

find . -type f -exec sh -c 'tail -n 1 "$1" | grep -q "?>" && printf "%s\n" "$1"' -- {} \;

And this gives me a list of all the files that end with the PHP tag which is expected but the list is also over 500 files long so it would take a lot of time to manually go through.

I'm looking for a relatively easy way to do this if it is possible.

I've tried using sed like so:

 find . -type f -exec sh -c 'tail -n 1 "$1" | grep -q "?>" && printf "%s\n" "$1"' -- {} \; | sed -i '$ d' ./*

But this has two issues; it doesn't go into directories and it removes the last line from all files rather than just the ones that have the PHP closing tag.

I am expecting it to find all files with ?> on the very last line (I can get this to work) and then delete that last line with the tag.

I feel like I'm quite close, just missing something.

1 Answers

To remove last line that contains ?> you may use

sed '${/?>/d;}'

The '${/?>/d;}' means:

  • $ - get the last line only
  • /?>/ - match the line only if it contains ?> text
  • d - delete the line.

To recursively run the sed command on a directory use

cd /your/dir/here && find . -type f -print0 | xargs -0 sed -i '${/?>/d;}'

See more specific solutions for recursive file matching at How to do a recursive find/replace of a string with awk or sed?

Related