Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove lines of data in the middle of a text file with Ruby

I know how to write to a file, and read from a file, but I don't know how to modify a file besides reading the entire file into memory, manipulating it, and rewriting the entire file. For large files this isn't very productive.

I don't really know the difference between append and write.

E.g.

If I have a file containing:

Person1,will,23
Person2,Richard,32
Person3,Mike,44

How would I be able just to delete line containing Person2?

like image 836
Senjai Avatar asked May 19 '13 19:05

Senjai


People also ask

How do you delete a file in Ruby?

To delete a file you need to use #delete command of the File class. You can use ruby's "fileutils" module to achieve deleting folders/directories. Let us say that I have to delete a folder at C:\Users\adhithya\desktop\ called "demo" that needs to be deleted.


1 Answers

You could open the file and read it line by line, appending lines you want to keep to a new file. This allows you the most control over which lines are kept, without destroying the original file.

File.open('output_file_path', 'w') do |output| # 'w' for a new file, 'a' append to existing
  File.open('input_file_path', 'r') do |input|
    line = input.readline
    if keep_line(line) # logic here to determine if the line should be kept
      output.write(line)
    end
  end
end

If you know the position of the beginning and end of the chunk you want to remove, you can open the file, read to the start, then seek to the end and continue reading.

Look up parameters to the read method, and read about seeking here:

http://ruby-doc.org/core-2.0/IO.html#method-i-read

like image 156
Matt Avatar answered Sep 21 '22 03:09

Matt