从文本文件中搜索字符串并删除该行 RUBY [英] search a string from a text file and delete that line RUBY

查看:34
本文介绍了从文本文件中搜索字符串并删除该行 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屋!

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