Re: [問題] 檔案複製

看板Perl作者 (What?)時間16年前 (2009/04/20 15:43), 編輯推噓2(202)
留言4則, 2人參與, 最新討論串2/2 (看更多)
※ 引述《yanganto (雙劍‧日光燈)》之銘言: : 因為要在很多個檔案中挑出我需要的檔案,並且複製到另外一個資料夾,然後須要挑的 : 檔案在一個htm的檔案裡面有寫。 : 我利用一個array去選擇要挑的檔案,結果複製的檔案會一個有內容一個沒內容這樣交替 : 不知道錯誤在哪裡,可以麻煩板上高手指證一下嗎?謝謝 : 剛開始學perl,寫的有點亂,不知道有沒有比較簡潔一點的方法^^" : 後來code改成這樣,但是還是會一個有抓到一個沒抓到這樣@@",不知道有沒有人能指導 : 一下,謝謝 : use strict; : my @list; : my $txt; : open(L,'/Users/yanganto/Desktop/list.txt'); : while(<L>){ : $txt = $_; : chomp($txt); : @list = (@list,$txt); : } : my $i=0; : my $file; : for($i=0;$i<=413;$i++){ : $file = glob("/Users/yanganto/Desktop/Minimization/$list[$i]/Output/*.msv"); : system("cp $file /Users/yanganto/Desktop/5Cal/"); : } 因為 glob() 可能回傳一個以上相符的檔名 所以單純使用 $file = glob(...) 會只得到第一個相符的檔名 請參考 http://perldoc.perl.org/functions/glob.html 此外,在 for loop 的 413 可改為 $#list 比較安全 下面是我改寫的版本,註解包含我這樣寫的原因, 希望對你有幫助^^ #!/usr/bin/perl use warnings; use strict; use File::Copy; our $list = '/Users/yanganto/Desktop/list.txt'; open (L, $list) or die "cannot open file '$list'\n"; our $basedir = '/Users/yanganto/Desktop'; while (<L>) { # 使用 loop,而不是一次將所有的 list 載入 chomp; my $dir = "$basedir/Minimization/$_/Output"; next if !-d $dir; # 先移至 $dir 工作目錄,這是預防 $dir 包含 glob() # 所使用的特殊字元 (如 []),造成 glob("$dir/*.msv") # 輸出錯誤的結果 chdir $dir; # glob() 可能回傳一個以上的檔名 # 請參考 http://perldoc.perl.org/functions/glob.html while (my $file = glob("*.msv")) { my $newfile = "$basedir/5Cal/$file"; # 避免覆蓋相同檔名的檔案 die "file '$newfile' exists\n" if -e $newfile; copy $file, $newfile or die "cannot copy file '$file' to '$newfile': $!\n"; } } close L; -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.230.108

04/20 19:14, , 1F
感謝你...我試試:)
04/20 19:14, 1F

04/20 19:23, , 2F
耶...解決了太感謝你了:)
04/20 19:23, 2F

04/20 20:02, , 3F
其實你用 </path/to/*.msv> 應該也不會有問題才對 (?)
04/20 20:02, 3F

04/20 20:04, , 4F
或者直接用 File::Find::Rule
04/20 20:04, 4F
文章代碼(AID): #19x2Um38 (Perl)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):
文章代碼(AID): #19x2Um38 (Perl)