简体   繁体   中英

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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