我正在处理看起来像MS Office文档的字符串。注在本例中,有两个BOM“字符”,一个在字符串的开头,另一个在正文中。有时有几个角色,有时一个也没有。在Powershell控制台中,它们打印为?
<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:m="http://schemas.microsoft.com/office/2004/12/omml" xmlns="http://www.w3.org/TR/REC-html40"><head><meta http-equiv=Content-Type content="text/html; charset=unicode"><meta name=Generator content="Microsoft Word 14 (filtered medium)"><style><!--
/* Font Definitions */
@font-face
{font-family:Calibri;
panose-1:2 15 5 2 2 2 4 3 2 4;}
/* Style Definitions */
<snip - bunch of style defs>
--></style></head><body lang=EN-US link=blue vlink=purple><div class=WordSection1>
<p class=MsoNormal style='text-autospace:none'>
<span style='font-size:10.0pt;font-family:"Tahoma","sans-serif"'></span>
<span style='font-size:12.0pt;font-family:"Times New Roman","serif"'>Testing <o:p></o:p></span>
</p></div></body></html>字符串来自一个对象,所以我不能简单地用Get-Content强制UTF8编码。我还能怎么剥离它们呢?我并不担心这是有损的,因为这只是被输送到显示器上,因此想要剥离额外的字符。我还将剥离HTML。
发布于 2013-02-15 03:49:20
如果字符串中可能有其他实际的UTF8字符,则执行此操作的另一种方法是采用此方法。它假定字节顺序标记字符位于每个字符串的开头:
$bytes = @()
$strs | Foreach {$bytes += [byte[]][char[]]$_}
$memStream = new-object system.io.memorystream
$memStream.Write($bytes, 0, $bytes.Length)
$memStream.Position = 0
$reader = new-object system.io.streamreader($memStream, [System.Text.Encoding]::UTF8)
$reader.ReadToEnd()
$reader.Dispose()发布于 2015-02-26 02:20:14
下面是一个PowerShell脚本,我使用它从源文件中删除嵌入的UTF-8BOM字符:
$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
}发布于 2013-02-15 01:57:56
在请求帮助时,您应该包含用于获取输出的代码。这行得通吗?
$s = #your code that gets the output#
$s -replace "" #returns output without the characters或
( code that creates output ) -replace ""https://stackoverflow.com/questions/14879216
复制相似问题