使用 PowerShell,如何按行号从文本文件中删除一行?

Dan*_*iel 2 powershell

在 PowerShell 中,假设我想使用行号从 10 行文本文件中删除第 5 行,这是如何完成的?

Kei*_*ill 6

不像我想要的那么干净,但有诀窍:

$content = Get-Content foo.txt
$content | Foreach {$n=1}{if ($n++ -ne 5) {$_}} > foo.txt
Run Code Online (Sandbox Code Playgroud)

如果你安装了PSCX,你可以使用 Skip-Object cmdlet 让它更好一点:

$content = Get-Content foo.txt
$content | Skip -Index 4 > foo.txt
Run Code Online (Sandbox Code Playgroud)

请注意,-Index 参数是基于 0 的,这就是我使用 4 而不是 5 的原因。