改变排序对象行为

2024-03-21

使用映射到 Linux 共享的驱动器时,文件名区分大小写。 PowerShell 按预期处理此问题,但我想以类似于“C”语言环境中使用的排序顺序的方式对输出进行排序,这意味着按字符值从 U+0000 一直到 U+ 升序排序10FFFF(例如,“0foo”位于“Foo”之前,“Foo”位于“bar”之前,“bar”位于“foo”之前)

为了说明问题:

PS > gci Z:\foo | sort -casesensitive
xyz
Xyz
XYZ
yZ
YZ

所需输出:

XYZ
Xyz
YZ
xyz
yZ

我尝试将当前线程的文化变量设置为[System.Globalization.CultureInfo]::InvariantCulture,但我没有成功:

$thrd = [Threading.Thread]::CurrentThread
$thrd.CurrentCulture = [Globalization.CultureInfo]::InvariantCulture
$thrd.CurrentUICulture = $thrd.CurrentCulture

当我认为这与文化信息有关时,我是否已经接近了,或者我真的偏离了轨道?有人知道我应该从哪里开始吗?我猜我需要临时创建一个具有我想要的行为的 CultureInfo 实例,但就 CompareInfo 而言,它只有 getter,更不用说我不确定如何重载 Sort-Object 的 CompareInfo.Compare 函数需要使用 PowerShell 函数。或者这实际上是一个失败的原因,因为这是不可能的?

Edit

至少,是否可以先用大写字符排序,如 XYZ、Xyz、xyz、YZ、yZ?


我非常努力地寻找是否有办法改变sort-object方法本身但不起作用。但我可以使用 StringComparer 静态类来完成类似的事情,如此所示msdn 示例 http://msdn.microsoft.com/en-us/library/system.stringcomparer.ordinalignorecase.aspx.

为了回答你的最后一部分,

At the very least, would it be possible to sort with uppercase characters first, as in XYZ, Xyz, xyz, YZ, yZ?

[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
#>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

改变排序对象行为 的相关文章

随机推荐