From: "Jesús Gabriel y Galán" Date: 2012-06-04T23:12:04+09:00 Subject: Re: Read from several .txt files by a pattern and write the matched lines to a new file On Mon, Jun 4, 2012 at 4:01 PM, Robert Hansen wrote: > Robert Hansen wrote in post #1063024: >> $files = Array.new >> >> Dir.glob("**/Msg.log").entries.each { |n| $files.push(n) if >> File.file?(n) } >> puts "\n#{$files.size} files found\n" >> >> pattern = /(failed)/m >> >> $files.each do |element| >>          f = File.open(element, 'r') >>               lines = f.readlines >>               lines.each do |line| >>                   if line.match(pattern) >>              File.open('newfile.txt', 'w') do |write|  <-- Problem >>                      write.puts(line) >>                         end >>                      end >>                    end >>                      f.close >>                 end >> >> My problem is where the "if statement" begins. I am sorry to say that my >> compiler does not give me any error message, but the "newfile.txt" will >> not be created and therefore not written to. This makes no sense to me >> since I am a new beginner at Programming/scripting >> >> As for your code, >> >> "$ find . -type f -name Msg.log -exec fgrep failed {} + >newfile.txt" >> >> looks pretty and neat, but I am afraid it is way over my head. >> >> Kind regard, Robert Hansen > > > Somewhere in the script i changed the working directory, so it was my > mistake, but feel free to suggest better code. Everything will be > appreciated as I am still learning. It's always better to use the block form to open files. It ensures that they are closed even if there are exceptions. To iterate over the lines of a file one at a time I like to use File#foreach: pattern = /(failed)/m File.open('newfile.txt', 'w') do |out| Dir.glob("**/Msg.log").entries.each do |file| next unless File.file?(file) File.foreach(file) do |line| out.puts(line) if line.match(pattern) end end end Hope this helps, Jesus.