![]() |
|
Syntactic Confectionery Delight | |
PerlMonks |
Re: Changing string in specific line/position in a fileby GrandFather (Saint) |
on Oct 31, 2022 at 20:19 UTC ( #11147875=note: print w/replies, xml ) | Need Help?? |
The bottom line, as Corion suggests is that you can't, usually, simply replace a line in a file. Most file systems present files as a sequence of bytes and there is no facility to insert/remove bytes from the sequence. Editing a line usually implies a possible change in length. Most file systems don't support that so the only option is to rewrite the entire file. There are lots of ways to make such edit operations more or less efficient on disk/memory space and processor/io system time. But there are always compromises that need to be made depending on your situation. For example, in your case, if the file is small (say a few hundred MB or so), just read the whole thing into memory, do all the editing in memory, then write it back out. Although, actually, your data looks like it ought to be in a database. If that were the case then your task is trivial: update a single cell in a table (not so trivial for the database engine, but that's not your problem). Almost always its best to not overthink the plumbing - don't worry about performance unless performance becomes an issue. Rewriting a file once to make an edit should not be a problem in terms of performance, but getting the code right can be more subtle than you might think. Tools like sed don't do any particular magic, they read and rewrite the whole file to get the job done.
Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond
In Section
Seekers of Perl Wisdom
|
|