2014-09-18 157 views
0

這是我的代碼紅寶石腳本:看跌刪除重複循環

pattern = /066-\d\d\d\-\d\d\d\-\d\d\d\-\d\d\/
Dir['c:/WurtsmithClean/DRCs/*.txt'].each do |file| 
    next unless File.file?(file) 
     File.open(file) do |f| 
      f.each_line do |line| 
       if line.match(pattern) 
        ln = line.match(pattern) 
        file.gsub!('c:/WurtsmithClean/DRCs/', '') 
        file.gsub!('txt', 'pdf') 
        puts file + "," + ln.to_s 
       end 
      end 
     end 
end 

所以這個腳本看重的是「066 - ### - ### - ### - ##」匹配模式中所有文本文件在每行的c:/ WurtsmithClean/DRCs /目錄中,並輸出文件名和匹配,兩者之間用逗號分隔以便導入CSV。

但我一直在試圖弄清楚如何刪除重複的匹配,因爲它發現多個匹配具有相同的文件名相同的數字。我希望這些刪除。我嘗試過使用UNIQ()方法,但它似乎只適用於數組。雖然整個輸出在技術上是循環完成後的數組,但我不知道如何將最終輸出作爲數組引用並刪除重複項。

這裏的輸出是現在怎麼樣:

066-018-400-001-00 DRC#26.pdf,066-018-400-001-00 
066-018-400-001-00 DRC#26.pdf,066-018-400-001-00 
066-019-100-001-00 DRC#19.pdf,066-019-100-001-00 
066-019-100-001-00 DRC#19.pdf,066-019-100-001-00 
066-019-100-001-00 DRC#19.pdf,066-019-100-001-00 
066-019-100-001-00 DRC.pdf,066-019-100-001-00 
066-020-100-001-00 DRC#20.pdf,066-020-100-001-00 
066-020-100-001-00 DRC#20.pdf,066-020-100-001-00 
066-020-100-001-00 DRC#20.pdf,066-020-100-001-00 
066-020-100-001-00 DRC#20.pdf,066-020-100-001-00 

我希望它這樣的輸出(無重複):

066-018-400-001-00 DRC#26.pdf,066-018-400-001-00 
066-019-100-001-00 DRC#19.pdf,066-019-100-001-00 
066-019-100-001-00 DRC.pdf,066-019-100-001-00 
066-020-100-001-00 DRC#20.pdf,066-020-100-001-00 
+0

CarySwoveland no that does not wor k我需要使用匹配作爲發現將輸出匹配和其餘的線後..我只是想要數字 – emvee 2014-09-18 20:02:31

回答

1

您可以填寫沿途的陣列。一旦你完成,然後使用uniq

matches = [] 
pattern = /066-\d\d\d\-\d\d\d\-\d\d\d\-\d\d\/
Dir['c:/WurtsmithClean/DRCs/*.txt'].each do |file| 
    next unless File.file?(file) 
    File.open(file) do |f| 
    f.each_line do |line| 
     if line.match(pattern) 
     ln = line.match(pattern) 
     file.gsub!('c:/WurtsmithClean/DRCs/', '') 
     file.gsub!('txt', 'pdf') 
     matches << file + "," + ln.to_s 
     end 
    end 
    end 
end 
matches.uniq.each { |match| puts match } 
+0

THX這工作..我需要把一個「puts」在「matches.uniq!」前面。儘管 – emvee 2014-09-18 20:14:55

+0

只是遍歷數組的每個元素。答案已更新。 – 2014-09-18 20:19:18

1

也許你可以做這樣的事情,每個文件:

首先,我會進行測試的小文件:

FNAME= 'test1' 

text =<<_ 
pig11 
cat12 
hat13 
rat14 
dog15 
_ 

File.write(FNAME, text) 

現在讓我們來看看對第一線該文件匹配模式/t\d+/(說),然後提取數字:

pattern = /t(\d+)/ 
File.open(FNAME) do |f| 
    ln = f.find { |l| l =~ pattern } 
    puts "found '#{ln[pattern,1]}' in line #{ln.chomp} in file #{FNAME}" if ln 
end 
    #=> found '12' in line cat12 in file test1