Return 行号与 Ruby readline
Return line number with Ruby readline
正在寻找一个简单的 ruby/bash 解决方案来调查日志文件,例如 apache 访问日志。
我的日志包含以字符串开头的行“授权:”
脚本的目标是 return 整个下一行,但在此匹配之后一行,其中包含字符串“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
我的问题与 if 条件有关。
如何从 readline 中获取行 number/caller,并在第二步中获取行 return 整个下一行 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
也许是这样的:
log_snapshot.each_with_index.reverse_each do |line, n|
case (line)
when /authorization:/
puts '%d: %s' % [ n + 1, line ]
end
end
其中 each_with_index
用于生成 0 索引的行号。我已切换为 case
样式,以便您可以更灵活地匹配不同的条件。例如,您可以添加 /i
标志来真正轻松地进行不区分大小写的匹配,或者在开头添加 \A
以将其锚定在字符串的开头。
另一件要考虑使用 File.open
块方法的事情,如下所示:
File.open(args[:apache_access_log], "r") do |f|
f.readlines.each_with_index.reverse_each do |line, n|
# ...
end
end
其中消除了显式 close
调用的需要。块的末尾自动为您关闭它。
正在寻找一个简单的 ruby/bash 解决方案来调查日志文件,例如 apache 访问日志。
我的日志包含以字符串开头的行“授权:”
脚本的目标是 return 整个下一行,但在此匹配之后一行,其中包含字符串“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
我的问题与 if 条件有关。 如何从 readline 中获取行 number/caller,并在第二步中获取行 return 整个下一行 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
也许是这样的:
log_snapshot.each_with_index.reverse_each do |line, n|
case (line)
when /authorization:/
puts '%d: %s' % [ n + 1, line ]
end
end
其中 each_with_index
用于生成 0 索引的行号。我已切换为 case
样式,以便您可以更灵活地匹配不同的条件。例如,您可以添加 /i
标志来真正轻松地进行不区分大小写的匹配,或者在开头添加 \A
以将其锚定在字符串的开头。
另一件要考虑使用 File.open
块方法的事情,如下所示:
File.open(args[:apache_access_log], "r") do |f|
f.readlines.each_with_index.reverse_each do |line, n|
# ...
end
end
其中消除了显式 close
调用的需要。块的末尾自动为您关闭它。