简体   繁体   English

用Ruby readline返回行号

[英]Return line number with Ruby readline

searching for a simple ruby/bash solution to investigate a logfile, for example an apache access log. 搜索简单的ruby / bash解决方案以调查日志文件,例如apache访问日志。

my log contains lines with beginning string " authorization: " 我的日志包含以开头字符串“ authorization: ”开头的行

goal of the script is to return the whole next but one line after this match, which contains the string " x-forwarded-for ". 脚本的目标是返回整个下一行,但返回此匹配项后的一行,其中包含字符串“ x-forwarded-for ”。

host: 10.127.5.12:8088^M
accept: */*^M
date: Wed, 19 Apr 2019 22:12:36 GMT^M
authorization: FOP ASC-amsterdam-b2c-v7:fkj9234f$t34g34rf=^M
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0)
x-forwarded-for: 195.99.33.222, 10.127.72.254^M
x-forwarded-host: my.luckyhost.com^M
x-forwarded-server: server.luckyhost.de^M
connection: Keep-Alive^M
^M

My question relates to the if condition. 我的问题与if条件有关。 How can I get the line number/caller from readline and in second step return the whole next line with x-forwarded-for . 如何从readline获取行号/呼叫者,并在第二步中使用x-forwarded-for返回下一行。

file = File.open(args[:apache_access_log], "r")
log_snapshot = file.readlines
file.close

log_snapshot.reverse_each do |line|
  if line.include? "authorization:"
    puts line

  end
end

Maybe something along these lines: 也许遵循以下思路:

log_snapshot.each_with_index.reverse_each do |line, n|
  case (line)
  when /authorization:/
    puts '%d: %s' % [ n + 1, line ]
  end
end

Where each_with_index is used to generate 0-indexed line numbers. 其中each_with_index用于生成0索引的行号。 I've switched to a case style so you can have more flexibility in matching different conditions. 我已切换到case样式,因此您可以在匹配不同条件时具有更大的灵活性。 For example, you can add the /i flag to do a case-insensitive match really easily or add \\A at the beginning to anchor it at the beginning of the string. 例如,您可以添加/i标志以真正轻松地进行不区分大小写的匹配,或者在开头添加\\A以便将其锚定在字符串的开头。

Another thing to consider using the block method for File.open , like this: 使用File.open的块方法要考虑的另一件事,像这样:

File.open(args[:apache_access_log], "r") do |f|
  f.readlines.each_with_index.reverse_each do |line, n|
    # ...
  end
end

Where that eliminates the need for an explicit close call. 在那里,消除了显式close调用的需要。 The end of the block closes it for you automatically. 块的结尾会自动为您关闭。

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

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