如何查找目录中包含 UTF-8 BOM(字节顺序标记)的所有文件?

Bor*_*ard 8 windows search utf-8

在 Windows 上,我需要在包含 UTF-8 BOM(字节顺序标记)的目录中查找所有文件。哪个工具可以做到这一点以及如何做到这一点?

它可以是 PowerShell 脚本、某些文本编辑器的高级搜索功能或其他任何东西。

vcs*_*nes 16

这是 PowerShell 脚本的示例。它在C:路径中查找前 3 个字节是0xEF, 0xBB, 0xBF.

Function ContainsBOM
{   
    return $input | where {
        $contents = [System.IO.File]::ReadAllBytes($_.FullName)
        $_.Length -gt 2 -and $contents[0] -eq 0xEF -and $contents[1] -eq 0xBB -and $contents[2] -eq 0xBF }
}

get-childitem "C:\*.*" | where {!$_.PsIsContainer } | ContainsBOM
Run Code Online (Sandbox Code Playgroud)

是否有必要“ReadAllBytes”?也许只读取几个第一个字节会表现更好?

有道理。这是一个仅读取前 3 个字节的更新版本。

Function ContainsBOM
{   
    return $input | where {
        $contents = new-object byte[] 3
        $stream = [System.IO.File]::OpenRead($_.FullName)
        $stream.Read($contents, 0, 3) | Out-Null
        $stream.Close()
        $contents[0] -eq 0xEF -and $contents[1] -eq 0xBB -and $contents[2] -eq 0xBF }
}

get-childitem "C:\*.*" | where {!$_.PsIsContainer -and $_.Length -gt 2 } | ContainsBOM
Run Code Online (Sandbox Code Playgroud)

  • 这拯救了我的一天!还了解到`get-childitem -recurse` 也可以处理子目录。 (2认同)