Got that grep portion working, thanks for reminding me about it! It's something I should use daily but just haven't taken the time to really learn yet.
You could delete and recreate the file at the end of the script.
Or copy the contents, empty the file, then do the mysql stuff after to make sure no extra stuff is added whilst it's all going on.
I'll give it a shot and let you know how I've fucked things up!