我已经能够追踪到基本的头/尾功能:
head -10 myfile <==> cat myfile | select -first 10
tail -10 myfile <==> cat myfile | select -last 10但是,如果我想列出除最后三行之外的所有行,或者列出除前三行之外的所有行,该如何做呢?在Unix中,我可以使用"head -n-3“或"tail -n+4”。对于PowerShell,应该如何做到这一点还不是很明显。
发布于 2012-04-10 06:14:41
与-First和-Last参数一样,还有一个-Skip参数可以提供帮助。值得注意的是,-Skip是基于1的,而不是零。
# this will skip the first three lines of the text file
cat myfile | select -skip 3我不确定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)
}
}作为演示:
# this would display the entire file except the last five lines
cat myfile | Skip-Last -count 5发布于 2012-04-12 04:30:37
在这里,有用的信息分布在其他答案中,但我认为有一个简洁的总结是有用的:
除 first three之外的所有行
1..10 | Select-Object -skip 3
returns (one per line): 4 5 6 7 8 9 10除了 three之外的所有行
1..10 | Select-Object -skip 3 -last 10
returns (one per line): 1 2 3 4 5 6 7也就是说,您可以使用内置的PowerShell命令来完成这项工作,但是必须指定大小是一件烦人的事情。一个简单的解决方法是只使用一个大于任何可能输入的常量,并且您不需要事先知道大小:
1..10 | Select-Object -skip 3 -last 10000000
returns (one per line): 1 2 3 4 5 6 7一个更简洁的语法是使用来自PowerShell社区扩展的Skip-Object cmdlet (Goyuix的答案中的Skip-Last函数执行相同的功能,但使用PSCX使您不必维护代码):
1..10 | Skip-Object -last 3
returns (one per line): 1 2 3 4 5 6 7First three lines
1..10 | Select-Object –first 3
returns (one per line): 1 2 3Last three lines
1..10 | Select-Object –last 3
returns (one per line): 8 9 10中 four lines
(这是因为无论调用中参数的顺序如何,-skip都是在-first之前处理的。)
1..10 | Select-Object -skip 3 -first 4
returns (one per line): 4 5 6 7发布于 2012-04-10 06:37:48
如果您使用的是PowerShell Community Extensions,则有一个Take-Object cmdlet,它将传递除最后N项之外的所有输出,例如:
30# 1..10 | Skip-Object -Last 4
1
2
3
4
5
6https://stackoverflow.com/questions/10079572
复制相似问题