Re: 有關檔案內容搜尋

看板Perl作者 (笑哈哈)時間21年前 (2002/11/24 11:23), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/2 (看更多)
※ 引述《Armstrong (薰衣草)》之銘言: :  請問若我想要在一個目錄下的多個檔案內容中 : 尋找出哪個檔案中有符合我想要字串的內容 : 並將有其內容的整行文字印到我開的另一個檔案中 : 我該如何作呢? :   假設檔案放在c:\my_doc :   有十幾個檔案 : 3q 你可以用grep這個公用程式來做, 不過還是附上一份perl code供你參考 我假設你是使用Win32環境下的Perl interpreter 把下面的code存成perl檔, 例如: search.pl 然後從命令列呼叫 C:\> search.pl [directory-name] [pattern] 例如: search.pl C:\my_doc "perl" ----------------------------------------------------------------- #! d:\Perl\bin\perl.exe sub search_in_directory { # STEP 1: Open the directory handle my($dirname, $pattern) = @_; opendir(DIRHANDLE, $dirname) || die "cannot opendir $dirname: $!"; # STEP 2: List the content of the specifed directory my(@entries) = readdir(DIRHANDLE); print "Searching $dirname\n"; # STEP 3: If the entry is a plain file, we shall do the fulltext search. # If the entry is a subdirectory, we shall lean into it! foreach $entry (@entries) { # Note: Remember to skip the . and .. entries if ($entry ne "." && $entry ne "..") { search_in_file("$dirname\\$entry", "$pattern") if -f "$dirname\\$entry"; search_in_directory("$dirname\\$entry", "$pattern") if -d "$dirname\\$entry"; } } # STEP 4: Close the directory handle closedir(DIRHANDLE); } sub search_in_file { # STEP 1: Open the file handle my($filename, $pattern) = @_; open(FILEHANDLE, $filename) || die "cannot open $filename: $!"; # STEP 2: Fulltext search work $lineno = 1; while (<FILEHANDLE>) { print "$filename [$lineno]: $_" if /$pattern/; $lineno++; } # STEP 3: Close the file handle close(FILEHANDLE); } search_in_directory(@ARGV); ---------------------------------------------------------------------- -- ※ 發信站: 批踢踢實業坊(ptt.csie.ntu.edu.tw) ◆ From: 140.112.30.182
文章代碼(AID): #zu4P50t (Perl)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):
文章代碼(AID): #zu4P50t (Perl)