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 reply to Re: Changing string in specific line/position in a file by GrandFather
in thread Changing string in specific line/position in a file by onemojofilter

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.