如何找到目錄中包含UTF-8 BOM(位元組順序標記)的所有檔案?

如何找到目錄中包含UTF-8 BOM(位元組順序標記)的所有檔案?

在 Windows 上,我需要尋找目錄中包含 UTF-8 BOM 的所有文件(位元組順序標記)。哪個工具可以做到這一點以及如何做到?

它可以是 PowerShell 腳本、某些文字編輯器的進階搜尋功能或其他任何東西。

答案1

以下是 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

是否有必要“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

答案2

附帶說明一下,這裡有一個 PowerShell 腳本,我用它從來源檔案中刪除 UTF-8 BOM 字元:

$files=get-childitem -Path . -Include @("*.h","*.cpp") -Recurse
foreach ($f in $files)
{
(Get-Content $f.PSPath) | 
Foreach-Object {$_ -replace "\xEF\xBB\xBF", ""} | 
Set-Content $f.PSPath
}

答案3

如果您使用的是權限受限的企業電腦(像我一樣)並且無法執行 powershell 腳本,您可以使用便攜式 Notepad++Python腳本外掛程式來執行任務,使用以下腳本:

import os;
import sys;
filePathSrc="C:\\Temp\\UTF8"
for root, dirs, files in os.walk(filePathSrc):
    for fn in files:
      if fn[-4:] != '.jar' and fn[-5:] != '.ear' and fn[-4:] != '.gif' and fn[-4:] != '.jpg' and fn[-5:] != '.jpeg' and fn[-4:] != '.xls' and fn[-4:] != '.GIF' and fn[-4:] != '.JPG' and fn[-5:] != '.JPEG' and fn[-4:] != '.XLS' and fn[-4:] != '.PNG' and fn[-4:] != '.png' and fn[-4:] != '.cab' and fn[-4:] != '.CAB' and fn[-4:] != '.ico':
        notepad.open(root + "\\" + fn)
        console.write(root + "\\" + fn + "\r\n")
        notepad.runMenuCommand("Encoding", "Convert to UTF-8 without BOM")
        notepad.save()
        notepad.close()

信用去往https://pw999.wordpress.com/2013/08/19/mass-convert-a-project-to-utf-8-using-notepad/

答案4

Powershell 測試前兩個位元組。 -eq 等運算子的右側成為字串。

dir -file | 
% { $utf8bom = '239 187' -eq (get-content $_.fullname -AsByteStream)[0..1]
    [pscustomobject]@{name=$_.name; utf8bom=$utf8bom} }

name        utf8bom
----        -------
foo           False
script.ps1     True
script.ps1~   False

相關內容