Powershell Select-String 后 Windows 上行数较少的更大 txt 文件

Bigger txt file with less rows on Windows after Powershell Select-String

我使用 Powershell Get-Content 和 -nomatch 运算符对一个文本文件应用了多个过滤器,然后将结果假脱机到一个文件中。

gc file.txt | {?_ -notmatch 'excl1|excl2|excl3'} | out-file newfile.txt

发生的情况是输出文件 (newfile.txt) 的行数较少,但 windows 报告的行数大于 file.txt。

有人遇到过这种行为吗?如何让 windows 报告正确的尺寸?我检查了行数,行数少的文件被报告为更大。

我确定您遇到了编码问题。默认情况下 Get-Content 使用 ascii 而 Out-File 使用 Unicode。

来自TechNet

-Encoding

Specifies the type of character encoding used in the file. Valid values are "Unicode", "UTF7", "UTF8", "UTF32", "ASCII", "BigEndianUnicode", "Default", and "OEM". "Unicode" is the default.

-Enconding asciiOut-File 一起使用,或者仅使用 Set-Content,因为它是 Get-Content 的合作伙伴。

Get-Content file.txt | {?_ -notmatch 'excl1|excl2|excl3'} | 
    out-file -Encoding ascii newfile.txt
    # or
    Set-Content newfile.txt

如果您的输入文件有问题,来自另一个方向 Get-Content PowerShell v3 及更高版本也支持 -Enconding