Deleting a specific line in a text file?

元气小坏坏 提交于 2019-12-21 04:49:22

问题


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.


回答1:


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".




回答2:


file.each do |line|
  if should_be_deleted(line)
    f.seek(-line.length, IO::SEEK_CUR)
    f.write(' ' * (line.length - 1))
    f.write("\n")
  end
end
file.close

File.new(filename).each {|line| p line }


来源:https://stackoverflow.com/questions/17638621/deleting-a-specific-line-in-a-text-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!