Find and Replace using function to manipulate matches first

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?

Answers


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:

normal: { x: 10, y: 6 }

that become

normal: { x: 5, y: 3 }

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.


with preg_replace you can replace the content by your custom function like this..: in this example the values 50 will be sent to the cnt function, calculated and sent back to the replace function..:

<?php
function cnt($x){
    return $x/2;
}

$txt="normal: { x: 50, y: 50 }";  //Replace this with content of your file
$x=preg_replace("/(normal: { x: )(\d+)(, y: )(\d+)( })/e", "'\\1'.cnt(\\2).'\\3'.cnt(\\4).'\\5'", $txt);
echo $x; //Output:  normal: { x: 25, y: 25 }
?>

you want to read the file in a string. Use preg_match to get the numbers you want to manipulate and then manipulate them. Then put those numbers back to the string and write the whole thing to file.


Need Your Help

Linux append console output to a logfile?

linux logging console

I know that I can let Linux to write the console output to a logfile by doing:

Resizable frame in Gui

java swing user-interface layout-manager

how to get non resizable frame in gui i confused about this because i am using setLayout(new FlowLayout()); so if i drag the size of the frame the location of my button is going to disarrange . her...