PowerShell 等效于“head

编程入门 行业动态 更新时间:2024-10-19 20:31:51
本文介绍了PowerShell 等效于“head -n-3"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I've been able to track down basic head/tail functionality:

head -10 myfile <==> cat myfile | select -first 10 tail -10 myfile <==> cat myfile | select -last 10

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

But if I want to list all lines except the last three or all lines except the first three, how do you do that? In Unix, I could do "head -n-3" or "tail -n+4". It is not obvious how this should be done for PowerShell.

推荐答案

与 -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

更多推荐

PowerShell 等效于“head

本文发布于:2023-11-30 04:21:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648703.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:PowerShell   head

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!