我必須查看大文件的最後幾行(典型大小爲500MB-2GB)。 我正在爲Windows Powershell尋找至關於Unix的命令tail
。 一些可供選擇的是, shell
http://tailforwin32.sourceforge.net/ app
和 編碼
Get-Content [filename] | Select-Object -Last 10
對我來講,不容許使用第一種替代方案,第二種方案是緩慢的。 有沒有人知道PowerShell的尾部有效實現。 spa
從PowerShell 3.0版開始,Get-Content cmdlet具備應該有用的-Tail參數。 有關Get-Content的信息,請參閱technet庫在線幫助。 .net
爲了完整起見,我將提到Powershell 3.0如今在Get-Content上有一個-Tail標誌 插件
Get-Content ./log.log -Tail 10
獲取文件的最後10行 code
Get-Content ./log.log -Wait -Tail 10
獲取文件的最後10行並等待更多 get
此外,對於那些* nix用戶,請注意大多數系統將cat別名爲Get-Content,所以這一般有效 cmd
cat ./log.log -Tail 10
很是基本,但無需任何插件模塊或PS版本要求便可知足您的需求: it
while ($true) {Clear-Host; gc E:\\test.txt | select -last 3; sleep 2 }
使用Powershell V2及如下版本,get-content會讀取整個文件,所以對我來講沒用。 如下代碼適用於我須要的內容,但字符編碼可能存在一些問題。 這其實是tail -f,可是若是你想向後搜索換行符,能夠很容易地修改它來獲取最後的x個字節,或者最後的x行。
$filename = "\wherever\your\file\is.txt" $reader = new-object System.IO.StreamReader(New-Object IO.FileStream($filename, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [IO.FileShare]::ReadWrite)) #start at the end of the file $lastMaxOffset = $reader.BaseStream.Length while ($true) { Start-Sleep -m 100 #if the file size has not changed, idle if ($reader.BaseStream.Length -eq $lastMaxOffset) { continue; } #seek to the last max offset $reader.BaseStream.Seek($lastMaxOffset, [System.IO.SeekOrigin]::Begin) | out-null #read out of the file until the EOF $line = "" while (($line = $reader.ReadLine()) -ne $null) { write-output $line } #update the last max offset $lastMaxOffset = $reader.BaseStream.Position }
我在這裏找到了大部分代碼。
只是對之前答案的一些補充。 爲Get-Content定義了別名,例如,若是您習慣使用UNIX,則可能須要cat
,而且還有type
和gc
。 而不是
Get-Content -Path <Path> -Wait -Tail 10
你能夠寫
# Print whole file and wait for appended lines and print them cat <Path> -Wait # Print last 10 lines and wait for appended lines and print them cat <Path> -Tail 10 -Wait