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

标签 regex powershell rename

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

目前文件命名为

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 }

}

最佳答案

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

$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"
    }
}

关于regex - 使用每个文件中的特定字符串重命名目录中的多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75071429/

相关文章:

regex - 如何使用正则表达式在逗号之间添加字符串和空值的引号

powershell - 如何使用Powershell将csv文件转换为小写或大写,以保持其结构?

基于向量 new_varname、old_varname 重命名 dplyr 中的变量名称

linux - 获取 Perl 重命名实用程序而不是内置重命名

使用 r 中的 start with 重命名多个列

javascript - 创建一个正则表达式以用相同字符替换字符串的每个匹配字符

regex - 如何计算 Rust 中的正则表达式匹配?

regex - 在 gedit 中,突出显示括号内的函数调用

xml - Powershell 和 XML : How to count specific elements for each node

Powershell 参数声明替代方案