Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting a specific line in a text file?

Tags:

file

ruby

line

How can I delete a single, specific line from a text file? For example the third line, or any other line. I tried this:

line = 2
file = File.open(filename, 'r+')
file.each { last_line = file.pos unless file.eof? }
file.seek(last_line, IO::SEEK_SET)
file.close

Unfortunately, it does nothing. I tried a lot of other solutions, but nothing works.

like image 323
bugerrorbug Avatar asked Jul 14 '13 10:07

bugerrorbug


People also ask

How do I delete a specific line?

Delete lines or connectorsClick the line, connector, or shape that you want to delete, and then press Delete. Tip: If you want to delete multiple lines or connectors, select the first line, press and hold Ctrl while you select the other lines, and then press Delete.


1 Answers

I think you can't do that safely because of file system limitations.

If you really wanna do a inplace editing, you could try to write it to memory, edit it, and then replace the old file. But beware that there's at least two problems with this approach. First, if your program stops in the middle of rewriting, you will get an incomplete file. Second, if your file is too big, it will eat your memory.

file_lines = ''

IO.readlines(your_file).each do |line|
  file_lines += line unless <put here your condition for removing the line>
end

<extra string manipulation to file_lines if you wanted>

File.open(your_file, 'w') do |file|
  file.puts file_lines
end

Something along those lines should work, but using a temporary file is a much safer and the standard approach

require 'fileutils'

File.open(output_file, "w") do |out_file|
  File.foreach(input_file) do |line|
    out_file.puts line unless <put here your condition for removing the line>
  end
end

FileUtils.mv(output_file, input_file)

Your condition could be anything that showed it was the unwanted line, like, file_lines += line unless line.chomp == "aaab" for example, would remove the line "aaab".

like image 57
Doodad Avatar answered Oct 13 '22 04:10

Doodad