3

我有一个包含一些数字的文本文件,我想搜索一个特定的数字然后删除该行。这是文件的内容

    83087
    308877
    214965
    262896
    527530

因此,如果我想删除 262896,我将打开文件,搜索字符串并删除该行。

4

1 回答 1

5

您需要打开一个临时文件来写入要保留的行。类似这样的事情应该这样做:

require 'fileutils'
require 'tempfile'

# Open temporary file
tmp = Tempfile.new("extract")

# Write good lines to temporary file
open('sourcefile.txt', 'r').each { |l| tmp << l unless l.chomp == '262896' }

# Close tmp, or troubles ahead
tmp.close

# Move temp file to origin
FileUtils.mv(tmp.path, 'sourcefile.txt')

这将运行为:

$ cat sourcefile.txt
83087
308877
214965
262896
527530
$ ruby ./extract.rb 
$ cat sourcefile.txt
83087
308877
214965
527530
$

您也可以仅在内存中执行此操作,而无需临时文件。但是根据您的文件大小,内存占用量可能很大。上述解决方案一次只在内存中加载一行,因此它应该可以在大文件上正常工作。

- 希望能帮助到你 -

于 2012-06-04T10:10:56.530 回答