[英]Ruby find a string in a text file and output the line it's found on
I need to add the functionality to output the entire line a string is found on. 我需要添加功能以输出在其上找到字符串的整行。 So here's the code I have working so far. 所以这是到目前为止我正在使用的代码。
if type == "asa"
if File.readlines(file).grep(/http server enabled/).any?
$httpserver_failures.push(file)
out.puts "FAILED: does have http enabled"
else
$httpserver_passes.push(file)
out.puts "PASSED: does not have http enabled"
end
elsif type == "ios"
if File.readlines(file).grep(/no ip http server/).any?
$httpserver_failures.push(file)
out.puts "FAILED: does have http enabled"
else
$httpserver_passes.push(file)
out.puts "PASSED: does not have http enabled"
end
end
So I just need to add a line to also output the line as it's found. 因此,我只需要添加一行以将找到的行也输出即可。 I just don't know the syntax. 我只是不知道语法。
Thanks 谢谢
grep
method takes a block also. grep
方法也需要一个块。 Thus I think you could write as below : 因此,我认为您可以这样写:
if type == "asa"
File.readlines(file).grep(/http server enabled/) do |line|
unless line.empty?
$httpserver_failures.push(file)
out.puts "FAILED: does have http enabled"
puts line # output the line
else
$httpserver_passes.push(file)
out.puts "PASSED: does not have http enabled"
end
end
elsif type == "ios"
File.readlines(file).grep(/no ip http server/) do |line|
unless line.empty?
$httpserver_failures.push(file)
out.puts "FAILED: does have http enabled"
puts line # output the line
else
$httpserver_passes.push(file)
out.puts "PASSED: does not have http enabled"
end
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.