如何使用Ruby删除文本文件中某些行的开始和结束的块?

时间:2012-02-23 10:48:01

标签: ruby string http net-http

我想使用Ruby从某些行开始和结束的文本文件中删除块。 我已生成包含HTTP请求响应的文本文件,但希望删除所有响应,只留下文件中的标题。响应块以reading all...行开头,以Conn close行结束。 如何从文本文件中删除这些块? 示例代码如下:

opening connection to 209.85.175.121...
opened
<- "GET / HTTP/1.1\r\nConnection: close\r\nHost: 209.85.175.121\r\nOrigin: 192.168.100.111\r\n\r\n"
-> "HTTP/1.1 404 Not Found\r\n"
-> "Date: Thu, 23 Feb 2012 10:40:39 GMT\r\n"
-> "Content-Type: text/html; charset=UTF-8\r\n"
-> "Server: ghs\r\n"
-> "Content-Length: 931\r\n"
-> "X-XSS-Protection: 1; mode=block\r\n"
-> "X-Frame-Options: SAMEORIGIN\r\n"
-> "Connection: close\r\n"
-> "\r\n"
reading 931 bytes...
-> "<!DOCTYPE html>\n<html lang=en>\n  <meta charset=utf-8>\n  <meta name=viewport content=\"initial-scale=1, minimum-scale=1, width=device-width\">\n  <title>Error 404 (Not Found)!!1</title>\n  <style>\n    *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}\n  </style>\n  <a href=//www.google.com/><img src=//www.google.com/images/errors/logo_sm.gif alt=Google></a>\n  <p><b>404.</b> <ins>That\342\200\231s an error.</ins>\n  <p>The requested URL <code>/</code> was not found on this server.  <ins>That\342\200\231s all we know.</ins>\n"
read 931 bytes
Conn close


    f = File.open("Access-Control-Allow-Origin.txt")
    text = f.read
    if text =~ /"Access-Control-Allow-Origin: *\r\n"/ then
    puts "#########\n\nFound ---> Access-Control-Allow-Origin: *\n\n#########"
    else
    puts "#########\n\nNo Access-Control-Allow-Origin: * found\n\n#########"
    end

如果条件允许的话。

1 个答案:

答案 0 :(得分:0)

您可以使用ruby flip-flop运算符来执行此操作:

def remove_unnecessary_lines(filename)
    lines = File.readlines(filename)

    File.open(filename, 'w') do |f|
        lines.each do |line|
            unless line =~ /^reading all...$/..line =~ /^Conn close$/
                f.puts line
            end
        end
    end
end

<强>更新

这是一个不同的问题,但是,如果我理解正确,您可以将代码放在lines.each内(就在unless之前):

if line =~ /"Access-Control-Allow-Origin: *\r\n"/ then
 puts "#########\n\nFound ---> Access-Control-Allow-Origin: *\n\n#########"
else
  puts "#########\n\nNo Access-Control-Allow-Origin: * found\n\n#########"
end