Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I modify or insert a line in a file?

Apache

How do I modify or insert a line in a file?

by  MikeLacey  Posted    (Edited  )
FAQ compiled and maintained by MikeLacey, contributions from yolond and stefanos. Please browse through faq219-2884 and faq219-2889 first. Comments on this FAQ and the General FAQ's are very welcome.

This isn't as easy as it sounds actually. There's no easy way to change just the one line of a variable record length text file, which most text files are. There's no way, at all, to insert data into the middle of a file.

What you have to do is read the file into memory (an array probably), close the file, make your changes, open the file for writing and write the whole thing back.

As long as the file isn't too big (too easily fit in memory) that approach works OK.

If the file *is* too big you have to:

Read the file, line by line, and write it out to a second file - complete with your changes, as you go. When you're done, delete the first file and rename the file you just created to have the same name as the first file.

yolond posted this code and I fiddled with it a bit, it's based upon the first approach above.

Code:
$input = "users.txt"
$id = 'line I want to edit';

open(INPUT, "<$users");  # open the file to read it
@data = <INPUT>;         # read the whole file into an array
close(INPUT);            # close the file

open (OUTPUT, ">$users"); # now open it to write to
flock(OUTPUT, 2);         # and lock it

for ($i=0;$i<$#data+1;$i++)    {         # for each line in the array
    chomp($data[$i]);                    # get rid of any trailing new-line character
    if ( $id eq $data[$i] )    {         # if it matches the data I'l looking for
        $data[$i] = "new data";          # replace it
        print OUTPUT "$data[$i]\n";      # write the changed line out to the file
    } else {                             # otherwise
	print OUTPUT "$data[$i]\n";      # write the unchanged line out to the file
    }
    
}

flock(OUTPUT, 8);    # unlock the file
close(OUTPUT);       # and close it

If you find a mistake, have a contribution to make or just want to buy me (or one of the other guys) a beer then drop me a line and I'll incorporate your change or whatever.

Mike



Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top