Ruby多个条件语句写入同一文件两次?

Ruby多个条件语句写入同一文件两次?,ruby,regex,if-statement,file-io,Ruby,Regex,If Statement,File Io,我正在尝试用ruby创建一个查找和替换脚本。但我不知道如何写入同一个文件两次,当有两个条件匹配时,两个不同的正则表达式模式被发现,需要在同一个文件中被替换,我可以让它提供两个文件副本,每个副本中只包含一个条件的更改 下面是我的代码,特别是pattern3和pattern4: print "What extension do you want to modify? " ext = gets.chomp if ext == "py" print("Enter password: " )

我正在尝试用ruby创建一个查找和替换脚本。但我不知道如何写入同一个文件两次,当有两个条件匹配时,两个不同的正则表达式模式被发现,需要在同一个文件中被替换,我可以让它提供两个文件副本,每个副本中只包含一个条件的更改

下面是我的代码,特别是pattern3和pattern4:

print "What extension do you want to modify? "
ext = gets.chomp

if ext == "py"
    print("Enter password: " )
    pass = gets.chomp

elsif ext == "bat"  
    print "Enter drive letter: "
    drive = gets.chomp
    print "Enter IP address and Port: "
    ipport = gets.chomp
end

pattern1 = /'Admin', '.+'/
pattern2 = /password='.+'/
pattern3 = /[a-zA-Z]:\\(?i:dir1\\dir2)/
pattern4 = /http:\/\/.+:\d\d\d\d\//


Dir.glob("**/*."+ext).each do |file|
        data = File.read(file)
            File.open(file, "w") do |f|
                if data.match(pattern1)
                    match = data.match(pattern1)
                      replace = data.gsub(pattern1, '\''+pass+'\'')  
                    f.write(replace)
                    puts "File " + file + " modified " + match.to_s
                elsif data.match(pattern2)
                    match = data.match(pattern2)
                      replace = data.gsub(pattern2, 'password=\''+pass+'\'')  
                    f.write(replace)
                    puts "File " + file + " modified "  + match.to_s
                end

                if data.match(pattern3)
                   match = data.match(pattern3)
                       replace = data.gsub(pattern3, drive+':\dir1\dir2')  
                     f.write(replace)
                     puts "File " + file + " modified "  + match.to_s
                if data.match(pattern4)
                     match = data.match(pattern4)
                       replace = data.gsub(pattern4, 'http://' + ipport + '/')  
                     f.write(replace)
                     puts "File " + file + " modified "  + match.to_s   
          end
    end
    end
end

f、 truncate0使事情变得更好,但会截断第一行,因为它从文件的第一个修改部分的末尾开始连接。

在所有替换之后只尝试写入一次文件:

print "What extension do you want to modify? "
ext = gets.chomp

if ext == "py"
    print("Enter password: " )
    pass = gets.chomp

elsif ext == "bat"  
    print "Enter drive letter: "
    drive = gets.chomp
    print "Enter IP address and Port: "
    ipport = gets.chomp
end

pattern1 = /'Admin', '.+'/
pattern2 = /password='.+'/
pattern3 = /[a-zA-Z]:\\(?i:dir1\\dir2)/
pattern4 = /http:\/\/.+:\d\d\d\d\//


Dir.glob("**/*.#{ext}").each do |file|
    data = File.read(file)
    data.gsub!(pattern1, "'#{pass}'")
    data.gsub!(pattern2, "password='#{pass}'")
    data.gsub!(pattern3, "#{drive}:\\dir1\\dir2")  
    data.gsub!(pattern4, "http://#{ipport}/")
    File.open(file, 'w') {|f| f.write(data)}
end