regex 在每个文件中使用特定字符串重命名目录中的多个文件

gj3fmq9x  于 2023-01-14  发布在  其他
关注(0)|答案(2)|浏览(83)

我有一个包含多个文件的文件夹,需要在文件夹内将它们重命名为字符串。字符串是交互的日期。
当前文件命名为

AUDIT-1.log
AUDIT-2.log
AUDIT-3.log

等等
我需要他们

AUDIT-11-08-22-1.log
AUDIT-11-07-22-2.log
AUDIT-11-08-22-3.log

我在当前代码迭代中遇到的问题是,收集所有文件的日期,并尝试使用所有日期重命名文件

示例:

NewName: 11-08-22 11-07-22 11-06-22 11-09-22 11-08-22 11-07-22 11-06-22 11-09-22-1.LOG
OldName: C:\TestTemp\AUDIT-2.LOG

每个文件中只有一个日期。

以下是我当前的代码:

$dir ="C:\TestTemp"
$files = Get-ChildItem -Path "$dir\*.log"
$RegexDate = '\d\d\/\d\d\/\d\d'

Measure-Command{

$file_map = @()
foreach ($file in $files) {
    $DateName= Get-Content $files | 
Select-String $RegexDate |
foreach-object { $_.Matches.Value } |
Select-Object
    $NewDateName= $DateName.replace('/','-')
$b = 1 
    $file_map += @{
        OldName = $file.Fullname
        NewName = "$NewDateName-$b.LOG" -f $(Get-Content $file.Fullname | Select-Object $NewDateName.Fullname)
    }
}

$file_map | ForEach-Object { Rename-Item -Path $_.OldName -NewName $_.NewName }

}
avwztpqn

avwztpqn1#

正如Santiago Squarzon在注解中指出的,立即解决的方法是用$files替换$file。为了代码简洁,可以实现以下单管道解决方案来获得相同的结果:

Select-String -Path "$dir\*.log" -Pattern '(\d+\/){2}\d+' | 
    Rename-Item -NewName { 
        $_.FileName -replace '-', "-$($_.Matches.Value.Replace('/','-'))-" 
    } -WhatIf

同样,正如在注解中提到的,使用Select-String允许阅读文件,这提供了通过Path属性的 * 参数绑定 * 直接管道传输到Rename-Item的机会。因此,使用脚本块进行新名称替换实际上是将从模式匹配中找到的值 * 插入 * 到-所在的文件名中。

  • 当您口述了所需结果后,可以删除-WhatIf安全/通用参数。*
dhxwm5r4

dhxwm5r42#

这将使用文件的最后一次写入时间来重命名文件。如果文件已经是该格式,则不会重命名。有一个哈希表来跟踪文件日期后缀的增量。这样,文件就可以按日期进行组织。

$dir = "C:\TestTemp"
$files = Get-ChildItem -Path "$dir\*.log"

#Hashtable to track the suffix for the files
[hashtable]$dateTracking = @{}

#Using padding to format the suffix with two digits, in case there more then 9 files
#incrase it if you have more then 99 files per day increase padding
$suffixPadding = '{0:d2}'

foreach ($file in $files) {
    #Don't rename files that were already renamed
    if ($file.Name -notmatch "AUDIT-\d{2}-\d{2}-\d{2}-\d{2}\.log") {
        $date = $file.LastWriteTime.ToString("MM-yy-dd")
        #If the date is not entered in the hashtable add it with suffix 01
        if (-not $dateTracking.ContainsKey($date)) {        
            $dateTracking.Add($date, $suffixPadding -f 1)
        }
        #Else increment suffix
        else {
            $dateTracking[$date] = $suffixPadding -f ([int]$dateTracking[$date] + 1)
        }
        #Here we use the date in the name of the file and getting the suffix from the hashtable
        Write-Host "Renaming $($file.Name) to AUDIT-$date-$($dateTracking[$date]).log"
        Rename-Item -Path $file -NewName "AUDIT-$date-$($dateTracking[$date]).log"
    }
}

相关问题