从文本文件中搜索字符串并删除该行RUBY
我有一个包含一些数字的文本文件,我想搜索特定的数字然后删除该行。 这是文件的内容
83087 308877 214965 262896 527530
因此,如果我想删除262896,我将打开文件,搜索字符串并删除该行。
您需要打开一个临时文件来写入要保留的行。 像这样的东西应该这样做:
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 $
您也可以仅在内存中执行此操作,而无需临时文件。 但内存占用量可能很大,具体取决于您的文件大小。 上面的解决方案一次只在内存中加载一行,所以它应该可以在大文件上正常工作。
- 希望能帮助到你 -