Hello Monks,

I have a text file made of short lines (line wrapping is not an issue, in case it makes a difference, although I doubt it does). I need to make a very simple change to this file. At some point a line looks like this: Name1 Address1. Then somewhere else in the file I have Name2 Address2. All I want to do is swap Address1 and Address2, as if the two people swapped homes.

I can read the entire file in the memory (I can also read and process it line by line so I don't use a whole lot of memory), then go line by line and write it to a new file as long as it is not the Name1 line. I have to stop there and keep searching for the other one, with Name2. Then extract Address2, rebuild the Name1 line write it to file, continue writing the other lines to the new file until I reach Name2 line and then doctor that one using Address1 which I carefully stored somewhere, then copy the rest of the lines. At the end I need to replace the original file with the new file I created.

Seems like a lot of trouble only for this. Any other solution?

Thanks!


In reply to In place file modification by RaduH

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.