简体   繁体   中英

How to read and print the line multiple strings appear on in Ruby

I have a log file with contents in this format:

[28/Feb/2017] 00007bd2 7d194700 - ERROR: ws_common: 
[28/Feb/2017] 00007bd2 7d194700 - ERROR: ESI: getResponse: failed 
[28/Feb/2017] 00007bd2 DOWN- [] ws_common: 

I want to find and print the line containing a keyword like "DOWN", as well as the time the message appears in the log file.

I did it like this in UNIX:

SomeVariable =`cat $filename| grep "$DD/$MTH/$YR:$HR:$MINM" | grep DOWN | wc -l

but I can't seem to get it right in Ruby. This returns ALL of the lines as well as the line numbers:

File.foreach("#{filename}").with_index do |line, line_num|

  if File.open("#{filename}") { |f| f.each.find { |line| line.include?("#
          {DAY}/#{MTH}/#{YR}:#{HR}:#{MINM}" && "down") }  }

    puts "#{line_num}: #{line} "
  end
end

Using the file above as an example, the output I would like to get from this is:

3 [28/Feb/2017] 00007bd2 DOWN- [] ws_common:

"3" being the third line.

I've done it like this in UNIX:

  SomeVariable =`cat $filename| grep "$DD/$MTH/$YR:$HR:$MINM" | grep DOWN | wc -l 

And here it's almost the same. This prints all lines with DOWN in them.

puts File.foreach(filename).grep(/DOWN/)
# >> [28/Feb/2017] 00007bd2 DOWN- 

I am not sure if you want to grep for timestamp or you want to simply know the timestamps of DOWN events. If it's the latter, here you have it (lines are printed in their entirety). If it's the former, it shouldn't be too hard to implement, now that you are armed with this new technique.

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