Board logo

标题: [问题求助] 用PowerShell保存为UTF-8无BOM[已解决] [打印本页]

作者: smss    时间: 2019-7-14 12:24     标题: 用PowerShell保存为UTF-8无BOM[已解决]

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

作者: Batcher    时间: 2019-7-14 13:14

https://www.pstips.net/out-fileutf8nobom.html
https://stackoverflow.com/questi ... s-encoding-to-utf-8
https://stackoverflow.com/questi ... hout-bom-powershell
作者: smss    时间: 2019-7-14 15:52

本帖最后由 smss 于 2019-7-14 15:53 编辑
  1. $str = [IO.File]::ReadAllText('manifest.xml', [Text.Encoding]::UTF8);
  2. $str = $str -replace '(?m)^\s+|\s*(?:\n|$)' -replace '<!--(?:(?!-->).)*-->';
  3. [IO.File]::WriteAllText('1.xml', $str, [Text.Encoding]::UTF8);
  4. $MyFile = Get-Content '1.xml'
  5. $Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False
  6. [System.IO.File]::WriteAllLines('1.xml', $MyFile, $Utf8NoBomEncoding)
复制代码
感觉能再改改
作者: xczxczxcz    时间: 2019-7-14 17:42

试试转为字节,再16进制,除前面3个字节,再转为字符串。我还没测试过。
作者: 523066680    时间: 2019-7-14 18:41

很直白的伪代码:
$UTF8 = $UTF8withBOM;
$UTF8 =~s/^\xef\xbb\xbf//;
write_file( "UTF8noBOM.txt",  {binmode=>":raw"}, $UTF8 );
作者: xczxczxcz    时间: 2019-7-15 11:25

昨晚试了下,PS的cmdlet及参数中还真没找到能把utf8-rom转utf8的。有可能姿势不对,但使用NET库就一句话搞定。
作者: smss    时间: 2019-7-15 14:46

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




欢迎光临 批处理之家 (http://bbs.bathome.net/) Powered by Discuz! 7.2