From: Robert Klemme Date: 2012-06-04T21:19:45+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 2:13 PM, Robert Hansen wrote: > Just to be said. I am new to ruby. > > This should iterate over an array of files, read them and match the > lines by a given pattern. And print to console, But how to proceed if i > want all of the matched lines to be written to a new file? You could invoke the script with an output redirection. That's just one option, of course. > $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) >                      puts line >                        end >                     end >                     f.close >                end > > > > I have tried different solutions as > File.open('newfile.txt', 'w') do |wirte| > write.puts(line) > > but it did not work What was the issue? Can you share an error message? > Any suggestions? Thanks Watch your spelling. Other than that: your task can be solved with other tools pretty easily $ find . -type f -name Msg.log -exec fgrep failed {} + >newfile.txt Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/