【问题标题】:Finding a file that has highest number in the filename using powershell使用powershell查找文件名中编号最高的文件
【发布时间】:2021-08-12 07:09:03
【问题描述】:

对不起,伙计们..我是 powershell 新手。如果有人在以下情况下提供帮助,那就太好了:

我在文件夹 c:\test 中有几个文件

sample.x.x.1
sample.x.x.2
sample.x.x.3
sample.x.x.4
sample.x.x.5

我想在给定文件夹中查找名称中编号最大的文件的名称。在上面的示例中,5 是最大的数字,脚本应将输出文件名返回为 sample.x.x.5

提前致谢!

【问题讨论】:

    标签: powershell powershell-3.0


    【解决方案1】:

    用数字对文件名进行排序是一个很大的问题,因为有两种方法。第一个将它们设置为按字母顺序。即0, 1, 11, 111, 2,...第二个使用自然顺序。即0, 1, 2, 11, 111...。这非常棘手,大约每三个程序员都对此感到困惑。

    已经有一个good answer,我会这样称呼它,

    # Create files 1..5
    for($i=1;$i -le 5; ++$i) { set-content sample.x.x.$i -Value $null } 
    
    # Tricksy! Create file .10 to confuse asciibetic/natural sorting
    set-content sample.x.x.10 -Value $null
    
    ls # Let's see the files
    
        Directory: C:\temp\test
    
    Mode                LastWriteTime         Length Name
    ----                -------------         ------ ----
    -a----       2015-09-28     10:29              0 sample.x.x.1
    -a----       2015-09-28     10:29              0 sample.x.x.10
    -a----       2015-09-28     10:29              0 sample.x.x.2
    -a----       2015-09-28     10:29              0 sample.x.x.3
    -a----       2015-09-28     10:29              0 sample.x.x.4
    -a----       2015-09-28     10:29              0 sample.x.x.5
    
    # Define helper as per linked answer
    $ToNatural = { [regex]::Replace($_, '\d+$', { $args[0].Value.PadLeft(20,"0") }) }
    
    # Sort with helper and check the output is natural result
    gci | sort $ToNatural -Descending | select -First 1
    
    Directory: C:\temp\test
    
    Mode                LastWriteTime         Length Name
    ----                -------------         ------ ----
    -a----       2015-09-28     10:29              0 sample.x.x.10
    

    【讨论】:

    • 也许值得注意的是 asciibetic/numerical 排序问题是由输入对象的 type 引起的。如果您知道要对哪个子字符串进行排序,只需将其转换为数字类型即可:sort { $_.Substring($_.LastIndexOf('.')+1) -as [int] }
    【解决方案2】:

    按字母排序。

    PS C:\Users\Gebb> @("sample.x.x.1", "sample.x.x.5", "sample.x.x.11") | sort
    sample.x.x.1
    sample.x.x.11
    sample.x.x.5
    

    数字排序。

    PS C:\Users\Gebb> @("sample.x.x.1", "sample.x.x.5", "sample.x.x.11") |
     sort -Property @{Expression={[Int32]($_ -split '\.' | select -Last 1)}}
    sample.x.x.1
    sample.x.x.5
    sample.x.x.11
    

    最大的数。

    PS C:\Users\Gebb> @("sample.x.x.1", "sample.x.x.5", "sample.x.x.11") |
     sort -Property @{Expression={[Int32]($_ -split '\.' | select -Last 1)}} |
     select -Last 1
    sample.x.x.11
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-21
      • 1970-01-01
      • 1970-01-01
      • 2013-12-31
      • 2010-12-07
      • 1970-01-01
      • 2011-06-10
      相关资源
      最近更新 更多