2014-01-23 57 views
1

有幾個問題已經是這樣,但沒有一個足夠具體用於我的目的。搜索特定字符串的10,000個日誌文件,然後輸出該字符串所在的每行,同時還創建該日誌文件的副本

我需要搜索特定字符串的10,000個日誌文件,然後輸出該字符串所在的每行,同時還創建該日誌文件的副本。

我幾乎在BATCH文件中工作..我想我打我的牆,需要開始使用PowerShell,我以前沒有用太多。

:更新

感謝Trondh,我能夠用自己的腳本作爲一個完美的基地,並把在我需要的功能。希望這可以幫助其他人:)

#Folder to search 
$folder = read-host "Please specify the location of the search " 

#Search for: 
$SearchTerm = read-host "type in the word you want to find Eg. Error or JobID " 

#Files to include in search 
$FileFilter = read-host "Enter Date Part of file filter Eg. 2014or 201401 " 

#File to store log file copies in 
$destinationfolder = "Backup-$SearchTerm" 

#File to store results in 
$newfile = "Search-Log-$SearchTerm.txt" 

#Get the files according to filter. Recurse, but exclude directories 
$files = Get-ChildItem -Path $folder -Include @("*$filefilter*.*") -recurse | where {$_.PSIsContainer -eq $false} 
foreach ($file in $files) 
    { 
     $result = $file | Select-String $SearchTerm 

     $result | add-content $newfile 

     New-Item -ItemType Directory -Force -Path $destinationfolder 

     #If we get a hit, copy the file 
     if ($result) 
      { 
       Write-host "Found match in file $($file.Name) ($($file.Directory))" 
       #Add result to file 
       $file | Copy-Item -Destination $destinationfolder 


       #Also output it 
       $result 

      } 

    } 


    Write-Host "Search Completed!" 

$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") 
+0

我的建議是使用以C++,C#,JAVA等爲本機(或幾乎)代碼輸出的語言。因爲批量解析文件需要很長時間 –

回答

1

這是我會怎麼做:

#Folder to search 
$folder = "D:\trond.hindenes\Desktop\test" 
#File to store log file copies in 
$destinationfolder = "D:\trond.hindenes\Desktop\test2" 
#Search for: 
$SearchTerm = "BAT" 
#Files to include in search 
$FileFilter = "file*" 

#Get the files according to filter. Recurse, but exclude directories 
$files = Get-ChildItem -Path $folder -Include $filefilter -recurse | where {$_.PSIsContainer -eq $false} 
foreach ($file in $files) 
    { 
     $result = $file | Select-String $SearchTerm 

     #If we get a hit, copy the file 
     if ($result) 
      { 
       Write-host "Found match in file $($file.Name) ($($file.Directory))" 
       #Add result to file 
       $file | Copy-Item -Destination $destinationfolder 

       #Also output it 
       $result 

      } 

    } 
+0

快速響應:)我會測試它謝謝! – HeXDeMoN

+0

那麼它搜索的字符串,但不會複製文件。 – HeXDeMoN

+0

對不起,沒有正確閱讀這個問題。查看更新的答案。 – Trondh

0
.... 
.... 
rem search for files that contain data 
for /f "tokens=*" %%f in ('findstr /s /i /m /c:"%word%" "%drive%\*%data%*.log"') do (

    rem copy the file selected by findstr to target folder 
    copy "%%~ff" "%targetFolder%" 

    rem and echo the lines with the data to the results file 
    findstr /n /i /c:"%word%" "%%~ff" >> "Search-Logs-Results-%word%.TXT" 
) 

findstr /m只是測試的文件中的字符串的存在,並保留第一個文件匹配,將文件名寫入stdout。文件列表使用for命令處理。對於每個文件,都會複製文件,然後將包含所需單詞的行發送到報告文件。

相關問題