删除文本文件中的特定行? [英] Deleting a specific line in a text file?

查看:399
本文介绍了删除文本文件中的特定行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

由于文件系统的限制,我认为您不能安全地这样做.

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)

您的条件可能是表明它是不需要的行的任何内容,例如file_lines += line unless line.chomp == "aaab"会删除"aaab"行.

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

这篇关于删除文本文件中的特定行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆