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.