在Powershell中合并txt文件时的UTF-8编码问题

我需要合并计算机上某个文件夹中的所有txt文件。它们有数百个,而且它们都有不同的名称,因此您必须手动键入文件名称以合并它们的任何代码对我来说都不起作用。这些文件采用“ UTF-8”编码,并包含来自不同语言的表情符号和字符(例如西里尔文字)以及带有重音符号的字符(例如é,ü,à...)。 一个stackoverflow-user友善的人让我在Powershell中运行了以下代码:

(gc *.txt) | out-file newfile.txt -encoding utf8

它非常适合合并文件。 但是,它实际上给了我一个带有“ UTF-8 with BOM”编码的txt文件,而不是带有“ UTF-8”编码的txt文件。此外,所有表情符号和特殊字符已被删除并交换为其他字符,例如用“¼”代替“ü”。这些表情符号和特殊字符保留下来对于我的工作非常重要。

有人可以帮助我调整此代码(或建议使用其他代码),以便为我提供一个合并的带有“ UTF-8”编码的txt文件,该文件仍包含所有特殊字符吗?请记住,我是一个外行。

非常感谢您的帮助和问候!

zyy63744753 回答:在Powershell中合并txt文件时的UTF-8编码问题

在PowerShell Out-File cmdlet没有Utf8NoBOM编码。
但是,您可以使用.NET编写不带BOM的Utf8文本文件:

以下所有方法的共同点

$rootFolder = 'D:\test'  # the path where the textfiles to merge can be found
$outFile    = Join-Path -Path $rootFolder -ChildPath 'newfile.txt'

方法1

# create a Utf8NoBOM encoding object
$utf8NoBom = New-Object System.Text.UTF8Encoding $false  # $false means NoBOM
Get-Content -Path "$rootFolder\*.txt" -Encoding UTF8 -Raw | ForEach-Object {
    [System.IO.File]::AppendAllText($outFile,$_,$utf8NoBom)
}

方法2

# create a Utf8NoBOM encoding object
$utf8NoBom = New-Object System.Text.UTF8Encoding $false  # $false means NoBOM
Get-ChildItem -Path $rootFolder -Filter '*.txt' -File | ForEach-Object {
    [System.IO.File]::AppendAllLines($outFile,[string[]]($_ | Get-Content -Encoding UTF8),$utf8NoBom)
}

方法3

# Create a StreamWriter object which by default writes Utf8 without a BOM.
$sw = New-Object System.IO.StreamWriter $outFile,$true  # $true is for Append
Get-ChildItem -Path $rootFolder -Filter '*.txt' -File | ForEach-Object {
    Get-Content -Path $_.FullName -Encoding UTF8 | ForEach-Object {
        $sw.WriteLine($_)
    }
}
$sw.Dispose()
,

没有-encoding参数,PS 5(gc)无法处理utf8没有bom输入文件:

(gc -Encoding Utf8 *.txt) | out-file newfile.txt -encoding utf8
本文链接:https://www.f2er.com/3139003.html

大家都在问