Ruby 在文本文件中查找字符串并输出找到它的行



我需要添加输出找到字符串的整行的功能。下面是我到目前为止的代码。

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

所以我只需要添加一行来输出找到的行。我只是不知道语法。

谢谢

grep方法也接受一个block。因此,我认为你可以这样写:

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

相关内容

  • 没有找到相关文章

最新更新