Philip Kirkbride
Philip Kirkbride

Reputation: 22889

Remove Lines with Ruby

How can I use ruby to open a text file, and remove lines containing a "key phrase".

I don't want only the key phrase to be removed, I need the full line which contains the phrase to be deleted.

Upvotes: 1

Views: 2374

Answers (3)

DavidGamba
DavidGamba

Reputation: 3613

Another approach is to use inplace editing inside ruby (not from the command line):

#!/usr/bin/ruby

def inplace_edit(file, bak, &block)
    old_argv = Array.new(ARGV)
    old_stdout = $stdout
    ARGV.replace [file]
    ARGF.inplace_mode = bak
    ARGF.lines do |line|
        yield line
    end
    ARGV.replace old_argv
    $stdout = old_stdout
end

inplace_edit 'test.txt', '.bak' do |line|
    print line unless line.match(/something/)
    print line.gsub(/search1/,"replace1")
end

If you don't want to create a backup then change '.bak' to ''.

Upvotes: 0

Michael Kohl
Michael Kohl

Reputation: 66837

Something like this:

File.open(output_file, "w") do |ofile|
  File.foreach(input_file) do |iline|
    ofile.puts(iline) unless iline =~ Key_phrase
  end
end

Upvotes: 5

inger
inger

Reputation: 20194

Is this a one-off, standalone task? Edit the file in place? If so the following one-liner might be handy:

ruby -i.bak -ne 'print unless /key phrase/' file-to-hack.txt

This changes the file, and backs up the original. If you want this as part of bigger program, add the loops around it for each line..

Upvotes: 1

Related Questions