On Mon, Jun 4, 2012 at 3:32 PM, Robert Hansen <lists / ruby-forum.com> wrote:
> $files =3D Array.new
>
> Dir.glob("**/Msg.log").entries.each { |n| $files.push(n) if
> File.file?(n) }
> puts "\n#{$files.size} files found\n"
>
> pattern =3D /(failed)/m
>
> $files.each do |element|
> =A0 =A0 =A0 =A0 f =3D File.open(element, 'r')
> =A0 =A0 =A0 =A0 =A0 =A0 =A0lines =3D f.readlines
> =A0 =A0 =A0 =A0 =A0 =A0 =A0lines.each do |line|
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0if line.match(pattern)
> =A0 =A0 =A0 =A0 =A0 =A0 File.open('newfile.txt', 'w') do |write| =A0<-- P=
roblem
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 write.puts(line)
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0end
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 end
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 end
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 f.close
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0end
>
> 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

You open and close the file all the time with 'w' which means 'open
for writing, truncate'.  This will lead to an empty file as you
notice.  You should open it only once because that is more efficient.
You could also replace 'w' with 'a' (append) but as I said, that is
far less efficient.

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

:-) Standard shell tools.

"find ." - finds in the directory hierarchy rooted at the current dir
"-type f" selects files
"name Msg.log" selects all items with name "Msg.log"
"-exec ... {} +" executed the given command with multiple file names
"fgrep failed" selects lines which contain the literal string "failed"
">newfile.txt" redirects output to the given file.

Kind regards

robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/