且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PowerShell 等效于“head -n-3"?

更新时间:2023-11-09 13:40:28

与 -First 和 -Last 参数一样,还有一个 -Skip 参数会有所帮助.值得注意的是,-Skip 是从 1 开始的,而不是零.

Like the -First and -Last parameters, there is also a -Skip parameter that will help. It is worth noting that -Skip is 1 based, not zero.

# this will skip the first three lines of the text file
cat myfile | select -skip 3

我不确定 PowerShell 是否可以为您返回除预构建的最后 n 行之外的所有内容.如果您知道长度,您可以从行数中减去 n 并使用 select 中的 -First 参数.您还可以使用仅在填充时通过行的缓冲区.

I am not sure PowerShell has something that gives you back everything except the last n lines pre-built. If you know the length you could just subtract n from the line count and use the -First parameter from select. You could also use a buffer that only passes lines through when it is filled.

function Skip-Last {
  param (
    [Parameter(Mandatory=$true,ValueFromPipeline=$true)][PsObject]$InputObject,
    [Parameter(Mandatory=$true)][int]$Count
  )

  begin {
    $buf = New-Object 'System.Collections.Generic.Queue[string]'
  }

  process {
    if ($buf.Count -eq $Count) { $buf.Dequeue() }
    $buf.Enqueue($InputObject)
  }
}

作为演示:

# this would display the entire file except the last five lines
cat myfile | Skip-Last -count 5