I’m trying to write a script that stores some data chunks inside flat .txt files (they’re small files, less than 100 lines).
Anyway, I’m trying to, in effect, update a single matching line with a new value for that line while leaving everything else alone in the file but cannot quite figure out how to modify just 1 line rather than replacing the full file.
Here is my code so far:
# get file contents as array.
array_of_lines = File.open( "textfile.txt", "r" ).readlines.map( &:chomp )
line_start = "123456:" # unique identifier
new_string = "somestring" # a new string to be put after the line_start indentifier.
# cycle through array finding the one to be updated/replaced with a new line.
# the line we're looking for is in format 123456:some old value
# delete the line matching the line_start key
array_of_lines.delete_if( |line| line_start =~ line )
# write new string into the array.
array_of_lines.push( "#{line_start}:#{new_string}" )
# write array contents back to file, replacing all previous content in the process
File.open( "textfile.txt", "w" ) do |f|
array_of_lines.each do |line|
f.puts line
end
end
The textfile.txt contents will always be consisting of the format:
unique_id:string_of_text
where I can match the unique_id using app data generated by the script to figure out which line of text to update.
Is there a better way of doing what I’m trying to?
It seems a little inefficient to read the entire file into memory, looping over everything just to update a single line in that file.
You can’t do what you want unless the new data you are writing is the same length as the old data.
If the length is different then all the bytes in the file after your modification need to be moved. Moving file data always involves rewriting everything (from the point of the modification onwards). In that case you might as well rewrite the whole file since your files are so small.
If the replacement data is the same length, then you can use
IO.seekto put the file pointer to the appropriate location, and then just usewriteto enter the replacement data.If you still don’t want to rewrite the whole file, but instead just move the data around (if replacement length is different), then you need to
seekto the correct location and thenwriteeverything to the end of the file from that point forward. If the replacement is shorter you will also need to callFile.truncateto resize the file.