删除文本文件中的特定行?

bug*_*bug 6 ruby file line

如何从文本文件中删除单个特定行?例如第三行或任何其他行.我试过这个:

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
Run Code Online (Sandbox Code Playgroud)

不幸的是,它什么也没做.我尝试了很多其他解决方案,但没有任何效果.

Doo*_*dad 9

我认为由于文件系统的限制,你不能安全地做到这一点.

如果您真的想进行就地编辑,可以尝试将其写入内存,编辑它,然后替换旧文件.但要注意这种方法至少存在两个问题.首先,如果您的程序在重写过程中停止,您将获得一个不完整的文件.其次,如果你的文件太大,它会占用你的记忆.

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
Run Code Online (Sandbox Code Playgroud)

这些方面的东西应该可行,但使用临时文件是一种更安全和标准的方法

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)
Run Code Online (Sandbox Code Playgroud)

你的情况可能是任何表明它是不需要的行的东西,file_lines += line unless line.chomp == "aaab"例如,会删除"aaab"行.