使用映射到Linux共享的驱动器时,文件名区分大小写.PowerShell按预期处理这个,但我想以类似于"C"语言环境中使用的排序顺序对输出进行排序,这意味着按字符值从U + 0000一直到U +按升序排序10FFFF(例如'0foo'出现在'Foo'之前,'Foo'出现在'bar'之前,'bar'出现在'foo'之前)
为了说明问题:
PS > gci Z:\foo | sort -casesensitive
xyz
Xyz
XYZ
yZ
YZ
Run Code Online (Sandbox Code Playgroud)
所需输出:
XYZ
Xyz
YZ
xyz
yZ
Run Code Online (Sandbox Code Playgroud)
我尝试将当前线程的文化变量设置为[System.Globalization.CultureInfo]::InvariantCulture,但我没有成功:
$thrd = [Threading.Thread]::CurrentThread
$thrd.CurrentCulture = [Globalization.CultureInfo]::InvariantCulture
$thrd.CurrentUICulture = $thrd.CurrentCulture
Run Code Online (Sandbox Code Playgroud)
当我认为它与文化信息有关时,我甚至关闭了,还是我真的偏离轨道?有谁知道我应该从哪里开始?我猜我需要暂时创建一个具有我想要的行为的CultureInfo实例,但是只有CompareInfo才有getter,更不用说我不确定如何重载SortInfo的CompareInfo.Compare函数需要使用PowerShell函数.或者这实际上是一个失败的原因,因为这是不可能的?
编辑
至少,是否可以先用大写字符排序,如XYZ,Xyz,xyz,YZ,yZ?
我真的很难找到是否有办法改变sort-object方法本身而不是工作.但是我使用StringComparer静态类完成了类似的事情,如msdn示例所示.
回答你的最后一部分,
At the very least, would it be possible to sort with uppercase characters first, as in XYZ, Xyz, xyz, YZ, yZ?
Run Code Online (Sandbox Code Playgroud)
[System.StringComparer]::InvariantCultureIgnoreCase是你的答案.为了看到差异,我尝试了下面的所有不同版本.
$arr = "0foo","xyz","Xyz","YZ","yZ","XYZ","Foo","bar"
$list = New-Object System.Collections.ArrayList
$list.AddRange($arr)
Write-host "CurrentCulture"
$list.Sort([System.StringComparer]::CurrentCulture);
$list
<# --------CurrentCulture--------
CurrentCulture
0foo
bar
Foo
xyz
Xyz
XYZ
yZ
YZ
#>
Write-Host "CurrentCultureIgnoreCase"
$list.Sort([System.StringComparer]::CurrentCultureIgnoreCase);
$list
<# --------CurrentCultureIgnoreCase--------
CurrentCultureIgnoreCase
0foo
bar
Foo
XYZ
Xyz
xyz
YZ
yZ
#>
Write-Host "InvariantCulture"
$list.Sort([System.StringComparer]::InvariantCulture);
$list
<# --------InvariantCulture--------
InvariantCulture
0foo
bar
Foo
xyz
Xyz
XYZ
yZ
YZ
#>
Write-Host "InvariantCultureIgnoreCase"
$list.Sort([System.StringComparer]::InvariantCultureIgnoreCase);
$list
<# --------InvariantCultureIgnoreCase--------
InvariantCultureIgnoreCase
0foo
bar
Foo
XYZ
Xyz
xyz
YZ
yZ
#>
Write-Host "Ordinal"
$list.Sort([System.StringComparer]::Ordinal);
$list
<# --------Ordinal--------
Ordinal
0foo
Foo
XYZ
Xyz
YZ
bar
xyz
yZ
#>
Write-Host "OrdinalIgnoreCase"
$list.Sort([System.StringComparer]::OrdinalIgnoreCase);
$list
<# --------OrdinalIgnoreCase--------
OrdinalIgnoreCase
0foo
bar
Foo
xyz
XYZ
Xyz
yZ
YZ
#>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1148 次 |
| 最近记录: |