开发者

Using PowerShell, how do I delete a line from a text file by its line number?

In PowerShell, say I 开发者_开发知识库want to delete line 5 from a 10 line text file using the line number, how is this done?


Not as clean as I would like but does the trick:

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

If you have PSCX installed, you can use the Skip-Object cmdlet to make this a little nicer:

$content = Get-Content foo.txt
$content | Skip -Index 4 > foo.txt

Note that the -Index parameter is 0 based which is why I used 4 instead of 5.


This is how I do it:

(cat SomeFile.txt) -replace (cat SomeFile.txt)[4],"" | sc SomeFile.txt -Force

Or in a slightly more readable form:

$LineNumber = 5
$Contents = Get-Content Somefile.txt
$Contents -replace $Contents[$LineNumber -1],"" | Set-Content Somefile.txt

Although I agree with Keith. Skip-Object can be very useful if you have the PSCX module installed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜