複数のShift-jisファイルをUTF-8に一括変換したい

SJISからUTF8に文字コードを変換します プログラム

文字コード変換アプリは新たにインストールすることなく、複数のShift-jisファイルを一括でUTF-8に変換する方法を調べました。

Windows

下記の状況におけるPowerShellサンプル例

・変換対象ファイル:*.sql

・変換元ディレクトリ:C:\Path\To\Your\Input\Directory

・変換先ディレクトリ:C:\Path\To\Your\Output\Directory

Get-ChildItem -Path C:\Path\To\Your\Input\Directory -Filter *.sql | ForEach-Object {
    $content = Get-Content $_.FullName
    $content = $content -replace "`r`n", "`n"  # 改行コードをLFに変換
    [System.IO.File]::WriteAllText("C:\Path\To\Your\Output\Directory\" + $_.Name, $content, [System.Text.Encoding]::UTF8)
}

Linux

下記の状況におけるコマンドサンプル例

・変換対象ファイル:*.sql

・変換元ディレクトリ:/path/to/your/input/directory

・変換先ディレクトリ:/path/to/your/output/directory

find /path/to/your/input/directory -type f -name "*.sql" -exec sh -c 'sed "s/\r$//" "{}" | iconv -f SJIS -t UTF-8 > "/path/to/your/output/directory/$(basename "{}")"' \;

Windows:vba

FileSystemObjectはutf-8対象外となるので、ADODB.Stream で utf-8ファイル保存します。

Sub ConvertFilesToUTF8_ADO()
    Dim sourceDir As String
    Dim destDir As String
    
    ' 入力ディレクトリと出力ディレクトリを指定
    sourceDir = "C:\Path\To\Your\Input\Directory" ' ご自身のディレクトリパスに変更
    destDir = "C:\Path\To\Your\Output\Directory"   ' ご自身のディレクトリパスに変更
    
    ' ディレクトリ内のファイルを変換
    ConvertFiles_ADO sourceDir, destDir
End Sub

Sub ConvertFiles_ADO(sourceDir As String, destDir As String)
    Dim fs As Object
    Dim sourceFile As Object
    Dim destFile As Object
    Dim content As String
    Dim utf8Bytes() As Byte
    
    ' FileSystemObject を作成
    Set fs = CreateObject("FileSystemObject")
    
    ' ソースディレクトリ内のすべてのファイルを取得
    For Each sourceFile In fs.GetFolder(sourceDir).Files
        ' ソースファイルの内容を読み込む
        Open sourceFile.Path For Input As #1
        content = Input$(LOF(1), 1)
        Close #1
        
        ' 改行コードをLFに変換
        content = Replace(content, vbCrLf, vbLf)
        
        ' Shift-JISからUTF-8に変換
        utf8Bytes = StrConv(content, vbFromUnicode)
        
        ' UTF-8の内容を新しいファイルに書き込む(ADODB.Streamを使用)
        WriteTextToFileUTF8_ADO sourceFile.Path, destDir & "\" & sourceFile.Name, utf8Bytes
    Next sourceFile
End Sub

Sub WriteTextToFileUTF8_ADO(sourceFilePath As String, destFilePath As String, contentBytes() As Byte)
    Dim adoStream As Object
    
    ' ADODB.Streamを作成
    Set adoStream = CreateObject("ADODB.Stream")
    
    ' バイナリ モードおよび UTF-8 エンコードを指定
    adoStream.Type = 1 ' adTypeBinary
    adoStream.Charset = "UTF-8"
    
    ' バイト データを書き込む
    adoStream.Open
    adoStream.Write contentBytes
    adoStream.SaveToFile destFilePath, 2 ' adSaveCreateOverWrite
    adoStream.Close
End Sub

Windows:sakuraエディタ

全選択してからSJISをUTF8に変換します。そして、改行コードを変換して保存します。

S_SelectAll();
S_SJIStoUTF8();
S_ReplaceAll(‘[\\r\\n]+’, ‘\\n’, 148); // すべて置換

//S_ReDraw(0); // 再描画
//S_FileSave( ); // 上書き保存
//S_FileClose( ); // 閉じる

※リファレンス :http://sakura.qp.land.to/SakuraMacro/reference/find/S_ReplaceAll.html

コメント