【问题标题】:Split and add text/number to the filename拆分并将文本/数字添加到文件名
【发布时间】:2017-04-17 10:15:56
【问题描述】:

我一直在尝试编写一个脚本来删除文件名的结尾部分并将其替换为构建的版本号。我尝试过修剪和拆分,但由于多余的点和正则表达式不好,我遇到了问题。

这些是文件示例:

Filename.Api.sow.0.1.1856.nupkg
something.Customer.Web.0.1.1736.nupkg

我想从这些文件名中删除0.1.18xx 并从变量中添加一个内部版本号。类似于1.0.1234.1233 (major.minor.build.revision)

所以最终结果应该是:

Filename.Api.sow.1.0.1234.1233.nupkg
something.Customer.Web.1.0.112.342.nupkg

这是我尝试拆分然后重命名的方法。但它不起作用。

$files = Get-ChildItem -Recurse | where {! $_.PSIsContainer}
foreach ($file in $files)
{
$name,$version = $file.Name.Split('[0-9]',2)
Rename-Item -NewName "$name$version" "$name".$myvariableforbuild
}

【问题讨论】:

    标签: powershell split rename trim file-manipulation


    【解决方案1】:

    你快到了。这里有一个正则表达式的解决方案:

    $myVariableForBuild = '1.0.1234.1233'
    Get-ChildItem 'c:\your_path' -Recurse | 
        where {! $_.PSIsContainer} | 
        Rename-Item -NewName { ($_.BaseName -replace '\d+\.\d+\.\d+$', $myVariableForBuild) + $_.Extension }
    

    【讨论】:

    • 如果你在 gci 中指定 -file,你可以删除你的 where
    • @Esperento57 他还在他的代码中使用了PsIsContainer,因此他很可能使用缺少-file 开关的PowerShell-v2。所以我可能在这里无法删除 where
    • 他没有指定他的版本。可能他也不知道 -file ;)
    【解决方案2】:

    可能不是最简洁的方法,但我会根据“.”拆分字符串,获取数组的最后一个元素(文件扩展名),然后遍历每个数组元素。如果它的非数字将其附加到一个新字符串,如果数字打破循环。然后将新版本和文件扩展名附加到新字符串中。

    $str = "something.Customer.Web.0.1.1736.nupkg"
    $arr = $str.Split(".")
    
    $extension = $arr[$arr.Count - 1]
    $filename = ""
    $newversion = "1.0.112.342"
    
    for ($i = 0 - 1; $i -lt $arr.Count; $i++)
    {
        if ($arr[$i] -notmatch "^[\d\.]+$")
        {
            # item is not numeric - add to string
            $filename += $arr[$i] + "."
        }
        else
        {
            # item is numeric - end loop
            break
        }    
    }
    
    # add the new version
    $filename += $newversion + "."
    
    # add the extension
    $filename += $extension
    

    显然它不是您问题的完整解决方案,但已经足够让您继续前进了。

    【讨论】:

      猜你喜欢
      • 2022-11-29
      • 1970-01-01
      • 2018-09-03
      • 1970-01-01
      • 1970-01-01
      • 2014-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多