2012-10-19 29 views
3

我想刪除文件中的重複行,但只刪除與特定正則表達式匹配的重複行,而將所有其他重複項保留在文件中。這是我現在有的:Ruby - 只刪除文件中的特定重複行

unique_lines = File.readlines("Ops.Web.csproj").uniq do |line|  
    line[/^.*\sInclude=\".*\"\s\/\>$/] 
end 

File.open("Ops.Web.csproj", "w+") do |file| 
    unique_lines.each do |line| 
    file.puts line 
    end 
end 

這將正確刪除重複的行,但只會將符合正則表達式的行添加回到文件中。我需要將文件中的所有其他行都添加回原樣。我知道我在這裏錯過了一些小東西。想法?

+0

是否結果的排序有關係嗎? –

回答

4

試試這個:

lines = File.readlines("input.txt") 
out = File.open("output.txt", "w+") 
seen = {} 

lines.each do |line| 
    # check if we want this de-duplicated 
    if line =~ /Include/ 
    if !seen[line] 
     out.puts line 
     seen[line] = true 
    end 
    else 
    out.puts line 
    end 
end 

out.close 

演示:

➜ 12980122 cat input.txt 
a 
b 
c 
Include a 
Include b 
Include a 
Include a 
d 
e 
Include b 
f 
➜ 12980122 ruby exec.rb 
➜ 12980122 cat output.txt 
a 
b 
c 
Include a 
Include b 
d 
e 
f 
+1

這是票。謝謝你的幫助! – Trent