[英]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
So if I want to delete 262896, I will open the file, search for the string and delete that line. 因此,如果我想删除262896,我将打开文件,搜索字符串并删除该行。
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')
This will run as : 这将运行如下:
$ 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. 上面的解决方案一次只在内存中加载一行,所以它应该可以在大文件上正常工作。
-- Hope it helps -- - 希望能帮助到你 -
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.