从文本文件中搜索字符串并删除该行 RUBY [英] search a string from a text file and delete that line RUBY
问题描述
我有一个包含一些数字的文本文件,我想搜索一个特定的数字,然后删除该行.这是文件的内容
I have a text file that contains some numbers and I want to search a specific number then delete that line. This is the content of the file
83087
308877
214965
262896
527530
所以如果我想删除 262896,我会打开文件,搜索字符串并删除该行.
So if I want to delete 262896, I will open the file, search for the string and delete that line.
推荐答案
您需要打开一个临时文件来写入要保留的行.类似这样的事情应该这样做:
You need to open a temporary file to write lines you want to keep. something along the lines like this should do it :
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
$
您也可以仅在内存中执行此操作,无需临时文件.但是内存占用可能会很大,具体取决于您的文件大小.上面的解决方案一次只在内存中加载一行,所以它应该可以在大文件上正常工作.
You can also do it in-memory only, without a temporary file. But the memory footprint might be huge depending on your file size. The above solution only loads one line at a time in memory, so it should work fine on big files.
--希望有帮助--
这篇关于从文本文件中搜索字符串并删除该行 RUBY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!