简体   繁体   English

从文本文件中搜索字符串并删除该行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

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.

相关问题 如果使用Ruby找到字符串,如何从$ stdout中搜索特定字符串并将整个$ stdout存储在文本文件中? - how to search particular string from $stdout and store whole $stdout in text file if string is found using Ruby? 从红宝石上的文件中删除文本行 - Remove line of text from file on ruby 来自文本文件的ruby tweet行 - ruby tweet line from text file 如何在文本文件中搜索字符串,然后打印/返回/输出在Ruby中作为数字找到的文件的哪一行 - How do I search a text file for a string and then print/return/put out what line of the file it was found on as a number in Ruby 从文本文件中删除一行信息 - Delete a line of information from a text file ruby - 从字符串中删除 - ruby - delete from a string 如何使用Ruby在文本文件中搜索完全匹配的字符串? - How to search for exact matching string in a text file using Ruby? Ruby在文本文件中找到一个字符串,然后输出在其上找到的行 - Ruby find a string in a text file and output the line it's found on Ruby脚本搜索字符串并删除整个原始文件? - Ruby script to search a string and delete entire raw? 如何用在Ruby文本文件中写入的每一行上找到的文件内容替换从控制台获取的URL中找到的特定字符串? - How to replace a particular string found in URL taken from console with file content found on each line written in text file in Ruby?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM