Windows Powershell中的Unix尾部等效命令

我必须查看大文件的最后几行(典型大小为500MB-2GB)。 我正在为Windows Powershell寻找至关于Unix的命令tail 。 一些可供选择的是, shell

http://tailforwin32.sourceforge.net/ app

编码

Get-Content [filename] | Select-Object -Last 10

对我来讲,不容许使用第一种替代方案,第二种方案是缓慢的。 有没有人知道PowerShell的尾部有效实现。 spa


#1楼

从PowerShell 3.0版开始,Get-Content cmdlet具备应该有用的-Tail参数。 有关Get-Content的信息,请参阅technet库在线帮助。 .net


#2楼

为了完整起见,我将提到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

#3楼

很是基本,但无需任何插件模块或PS版本要求便可知足您的需求: it

while ($true) {Clear-Host; gc E:\\test.txt | select -last 3; sleep 2 }


#4楼

使用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
}

我在这里找到了大部分代码。


#5楼

只是对之前答案的一些补充。 为Get-Content定义了别名,例如,若是您习惯使用UNIX,则可能须要cat ,而且还有typegc 。 而不是

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
相关文章
相关标签/搜索