简体   繁体   中英

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.

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 --

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM