【问题标题】:Ruby find a string in a text file and output the line it's found onRuby 在文本文件中查找一个字符串并输出它所在的行
【发布时间】:2014-03-17 15:31:53
【问题描述】:

我需要添加功能以输出找到字符串的整行。这是我目前工作的代码。

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

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

谢谢

【问题讨论】:

标签: ruby file readlines


【解决方案1】:

grep 方法也需要一个块。因此,我认为您可以编写如下:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-05
    • 2023-03-30
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    相关资源
    最近更新 更多