On Mon, Jun 4, 2012 at 3:32 PM, Robert Hansen <[email protected]> wrote:
> $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
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
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
-- You received this message because you are subscribed to the Google Groups
ruby-talk-google group. To post to this group, send email to
[email protected]. To unsubscribe from this group, send email
to [email protected]. For more options, visit this
group at https://groups.google.com/d/forum/ruby-talk-google?hl=en