PowerShell相当于"head -n-3"?

lik*_*kso 20 powershell tail unix-head

我已经能够追踪基本的头/尾功能:

head -10 myfile <==> cat myfile | select -first 10
tail -10 myfile <==> cat myfile | select -last 10
Run Code Online (Sandbox Code Playgroud)

但是如果我想列出除前三个以外的所有行或除前三个之外的所有行,你怎么做?在Unix中,我可以做"head -n-3"或"tail -n + 4".对于PowerShell应该如何做这一点并不明显.

Mic*_*ens 21

有用的信息在这里分布在其他答案中,但我认为有一个简明的总结是有用的:

三个以外的所有行

1..10 | Select-Object -skip 3
returns (one per line): 4 5 6 7 8 9 10
Run Code Online (Sandbox Code Playgroud)

除了所有行最后 3

1..10 | Select-Object -skip 3 -last 10
returns (one per line): 1 2 3 4 5 6 7
Run Code Online (Sandbox Code Playgroud)

也就是说,你可以使用内置的PowerShell命令完成它,但是必须指定进入的大小是一种烦恼.一个简单的解决方法是使用比任何可能的输入更大的常量,你不需要知道大小先验:

1..10 | Select-Object -skip 3 -last 10000000
returns (one per line): 1 2 3 4 5 6 7
Run Code Online (Sandbox Code Playgroud)

正如Keith Hill建议的那样,更清晰的语法是使用来自PowerShell社区扩展的Skip-Object cmdlet(Goyuix的答案中的Skip-Last函数执行等效,但使用PSCX可以使您不必维护代码):

1..10 | Skip-Object -last 3
returns (one per line): 1 2 3 4 5 6 7
Run Code Online (Sandbox Code Playgroud)

首先三行

1..10 | Select-Object –first 3
returns (one per line): 1 2 3
Run Code Online (Sandbox Code Playgroud)

最后三行

1..10 | Select-Object –last 3
returns (one per line): 8 9 10
Run Code Online (Sandbox Code Playgroud)

中间四行

(这是有效的,因为无论调用中的参数顺序如何,都会-skip在之前处理-first.)

1..10 | Select-Object -skip 3 -first 4
returns (one per line): 4 5 6 7
Run Code Online (Sandbox Code Playgroud)


Goy*_*uix 9

与-First和-Last参数一样,还有一个-Skip参数可以提供帮助.值得注意的是-Skip是基于1而不是零.

# this will skip the first three lines of the text file
cat myfile | select -skip 3
Run Code Online (Sandbox Code Playgroud)

我不确定PowerShell有什么可以让你回到除了预建的最后n行以外的所有东西.如果您知道长度,则可以从行计数中减去n并使用select中的-First参数.您还可以使用仅在填充时传递线的缓冲区.

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)
  }
}
Run Code Online (Sandbox Code Playgroud)

作为演示:

# this would display the entire file except the last five lines
cat myfile | Skip-Last -count 5
Run Code Online (Sandbox Code Playgroud)