Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: Changing string in specific line/position in a file

by GrandFather (Saint)
on Oct 31, 2022 at 20:19 UTC ( [id://11147875]=note: print w/replies, xml ) Need Help??


in reply to Changing string in specific line/position in a file

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
  • Comment on Re: Changing string in specific line/position in a file

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11147875]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2024-04-25 05:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found