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

时间:2015-03-30 20:11:09

标签: ruby regex if-statement file-io

我正在尝试在ruby中创建一个查找和替换脚本。但是,当有两个条件匹配时,我无法弄清楚如何写入同一个文件两次(找到2个不同的正则表达式模式并需要在同一个文件中替换)我可以让它提供2个仅用于连接的文件副本每个条件中的一个条件所做的更改。

这是我的代码(具体是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.truncate(0)使事情变得更好但截断了第一行,因为它从文件的第一个修改部分的末尾开始连续。

1 个答案:

答案 0 :(得分:0)

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

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