且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Powershell 从文件中删除最后一行

更新时间:2023-02-05 10:51:53

如果您已经知道文件的最后一件事是您想要摆脱的 CRLF(并且您也知道编码),您可以去快速路线:

If you already know that the very last thing of the file is a CRLF you want to get rid of (and you know the encoding too) you can go the quick route:

$stream = [IO.File]::OpenWrite('foo.txt')
$stream.SetLength($stream.Length - 2)
$stream.Close()
$stream.Dispose()

这是文件的就地截断.它无需将所有文件读入内存即可工作(如果您有一个非常 的大文件,那就太好了).它适用于 ASCII、Latin-* 和 UTF-8.它不适用于 UTF-16(在这种情况下,您必须从末尾删除四个字节).

This is an in-place truncation of the file. It works without reading all the file into memory (very nice if you have a very large file). It works for ASCII, Latin-* and UTF-8. It won't work that way for UTF-16 (you'd have to remove four bytes from the end, in that case).

您可以额外检查最后两个字节确实是您要删除的内容:

You can include an additional check that the last two bytes are really what you want to remove:

$stream = [IO.File]::Open('foo.txt', [IO.FileMode]::Open)
$stream.Position = $stream.Length - 2
$bytes = 0..1 | %{ $stream.ReadByte() }
$compareBytes = 13,10 # CR,LF
if ("$bytes" -eq "$compareBytes") {
    $stream.SetLength($stream.Length - 2)
}
$stream.Close()
$stream.Dispose()

再次,如果您使用其他编码,请进行调整,例如对于 UTF-16,您需要与 0,10,0,1310,0,13,0 进行比较.

Again, adapt if you use another encoding, e.g. for UTF-16 you need to compare to either 0,10,0,13 or 10,0,13,0.

同意,这不是 PowerShell-ey,但自从我不得不处理 700-MiB 的数据库转储后,我很担心将潜在的大文件完全读入内存 ;)

Agreed, this is not very PowerShell-ey, but ever since I had to process a 700-MiB database dump I am wary of reading potentially large files into memory completely ;)