2015-03-30 70 views
0

我想在ruby中創建一個查找和替換腳本。但我不知道如何在兩個條件匹配的情況下兩次寫入同一個文件(找到了兩個不同的正則表達式模式,並且需要在同一個文件中替換)我可以得到它只提供2個文件副本每個條件中的一個條件所做的更改。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.truncate(0)使事情更好,但會截斷第一行,因爲它從該文件的第一改性部的端concatonates 。所有置換後

回答

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