简体   繁体   English

如何读取和打印多行字符串显示在Ruby中

[英]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. 我想查找并打印包含诸如“ DOWN”之类的关键字的行,以及消息出现在日志文件中的时间。

I did it like this in UNIX: 我是在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. 但我似乎无法在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 [28 / Feb / 2017] 00007bd2下-[] ws_common:

"3" being the third line. 第三行是“ 3”。

I've done it like this in UNIX: 我在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. 这将打印所有带有DOWN行。

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. 我不确定是要时间戳还是grep还是只想知道DOWN事件的时间戳。 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. 如果是前者,那么既然您已经掌握了这项新技术,那么实施起来就不会太困难。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM