简体   繁体   English

Powershell:尾部最后一行并删除

[英]Powershell: Tail last line and remove it

How can I use powershell -tail param to remove the last line from a file? 如何使用powershell -tail参数删除文件的最后一行?

The following line gets the last line, but , when I set the content to the file it just stores that last line and disregards the rest... 下一行获得了最后一行,但是,当我将内容设置为文件时,它只存储了最后一行,而忽略了其余的...

Get-content $file -tail 1.

You can't 你不能

Get-Content -Tail $N only reads the last $N lines, it doesn't remove anything. Get-Content -Tail $N读取最后$N行,它不删除任何内容。

Most efficient way is probably using the System.IO.File.ReadAllBytes() and WriteAllBytes() methods: 最有效的方法可能是使用System.IO.File.ReadAllBytes()WriteAllBytes()方法:

# Read all lines
$LinesInFile = [System.IO.File]::ReadAllLines($file)
# Write all lines, except for the last one, back to the file
[System.IO.File]::WriteAllLines($file,$LinesInFile[0..($LinesInFile.Count - 2)])
# Clean up
Remove-Variable -Name LinesInFile

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM