简体   繁体   中英

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.

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

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

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

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