返回列表 发帖

[问题求助] 用PowerShell保存为UTF-8无BOM[已解决]

本帖最后由 smss 于 2019-7-17 19:17 编辑
$str = [IO.File]::ReadAllText('manifest.xml', [Text.Encoding]::UTF8);
$str = $str -replace '(?m)^\s+|\s*(?:\n|$)' -replace '<!--(?:(?!-->).)*-->';
[IO.File]::WriteAllText('1.xml', $str, [Text.Encoding]::UTF8);COPY

回复 6# xczxczxcz
$MyFile = Get-Content '1.xml'
$Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False
[System.IO.File]::WriteAllLines('1.xml', $MyFile, $Utf8NoBomEncoding)COPY
自测可以啊 先用Notepad++弄个有BOM 的1.xml 再运行可以正常啊

TOP

昨晚试了下,PS的cmdlet及参数中还真没找到能把utf8-rom转utf8的。有可能姿势不对,但使用NET库就一句话搞定。

TOP

很直白的伪代码:
$UTF8 = $UTF8withBOM;
$UTF8 =~s/^\xef\xbb\xbf//;
write_file( "UTF8noBOM.txt",  {binmode=>":raw"}, $UTF8 );
[url=][/url]

TOP

试试转为字节,再16进制,除前面3个字节,再转为字符串。我还没测试过。

TOP

本帖最后由 smss 于 2019-7-14 15:53 编辑
$str = [IO.File]::ReadAllText('manifest.xml', [Text.Encoding]::UTF8);
$str = $str -replace '(?m)^\s+|\s*(?:\n|$)' -replace '<!--(?:(?!-->).)*-->';
[IO.File]::WriteAllText('1.xml', $str, [Text.Encoding]::UTF8);
$MyFile = Get-Content '1.xml'
$Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False
[System.IO.File]::WriteAllLines('1.xml', $MyFile, $Utf8NoBomEncoding)COPY
感觉能再改改

TOP

我帮忙写的代码不需要付钱。如果一定要给,请在微信群或QQ群发给大家吧。
【微信公众号、微信群、QQ群】http://bbs.bathome.net/thread-3473-1-1.html
【支持批处理之家,加入VIP会员!】http://bbs.bathome.net/thread-67716-1-1.html

TOP

返回列表