简体   繁体   中英

Simple way to grep/filter file and store it in new file

I want to learn the simplest way to filter fileIN.txt and store results in fileOUT.txt. I have a logic to go thru each line, do grep and write line if match, but I think might something more powerful?

My file is 2G so I care about performance.

f = File.new("fileIN.txt")
text = f.read
if text =~ /foo|moo|woo/ then
  #write fileOUT.txt?
end

I would go with:

begin
  input = File.new('fileIN.txt', 'r')
  File.open('fileOut.txt', 'w') do |output|
    while line = file.gets
       output.write line if line =~ /foo|moo|woo/    
    end
  end
ensure
  input && input.close
end

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