I need to search for certain lines in a file that contain numbers, then do some manipulation on those numbers before replacing them in the file. For example, say I’ve got a line like this:
normal: { x: 50, y: 50 }
I need to find that line, divide both numbers by 2, then replace the numbers in the line and update the file. I have no problem writing the regex to find the line, and have written a little PHP script using preg_replace_callback() to manipulate the numbers, but I need to be able to replace the numbers then update just that line in the file. I’d be happy to use bash/sed/awk or Ruby or Python or PHP, but I’m not an expert on any of those.
Should I just read the whole file in, do my replace_callbacks then overwrite the file?
Yes. What you suggested is the best option.
Read the whole file, replace the numbers (you already did that), and write the whole file back.
In case you have a really huge file, you might run into trouble because it won’t fit into memory.
You can of course, scan the file, and only replace what you need to replace.
If you are going to fiddle with the filehandle, and overwrite only the bytes you need to overwrite (and leave the remainder of the file alone) you might find yourself in situations like:
that become
and thus you lost a byte because “10” becomes “5”. 🙂
In your example you can use a space instead, but I wouldn’t know if that would work in all situations you will encounter.
In short: do what you proposed yourself: read, manipulate, and write back.