Diffy
Diffy

Reputation: 735

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.

Upvotes: 3

Views: 6041

Answers (1)

leucos
leucos

Reputation: 18269

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

Upvotes: 5

Related Questions