简体   繁体   English

使用powershell重命名名称中间带有递增数字的文件

[英]Renaming files with incremented number in the middle of the name using powershell

I've searched long and hard for this, but cannot seem to locate a means of completing the renaming of files within multiple directories.我为此进行了长期而艰苦的搜索,但似乎无法找到一种方法来完成多个目录中文件的重命名。 The issue is that I need to insert a unique number sequence in the middle of a file name.问题是我需要在文件名中间插入一个唯一的数字序列。 Here are the examples of my file names:以下是我的文件名示例:

8675309_FileName1_ExtraSuff1_Extrastuff2 and some more stuff_012345.html
2020202_FileName2_ExtraSuff1_Extrastuff2 and some more stuff_012345.html
... etc.

Renamed to insert a copy of the 1st 7 fields, a numeric sequencing and a date as in the following:重命名以插入第 7 个字段的副本、数字排序和日期,如下所示:

8675309_8675309_00001_2022_FileName1_ExtraSuff1_Extrastuff2 and some more stuff_012345.html
2020202_2020202_00002_2022_FileName2_ExtraSuff1_Extrastuff2 and some more stuff_012345.html
... etc.

Here is what I've tried so far:这是我迄今为止尝试过的:

$i = 1 Get-ChildItem -Filter *.html | $i = 1 Get-ChildItem -Filter *.html | ForEach-Object{ Rename-Item -Path $ .FullName -NewName (($ .BaseName -split ' ')[0] + ' ' + ('{0:D5}' -f $i) + ' 2022' + ' Performance_Eval ' + ($ .BaseName -split ' ')[1] + ($ .BaseName -split ' ')[2] + ($ .BaseName -split ' ')[3] + ' ' + ($ .BaseName -split ' ')[4] + $_.Extension ) $i++ } ForEach-Object{ Rename-Item -Path $ .FullName -NewName (($ .BaseName -split ' ')[0] + ' ' + ('{0:D5}' -f $i) + ' 2022' + ' Performance_Eval ' + ($ .BaseName -split ' ')[1] + ($ .BaseName -split ' ')[2] + ($ .BaseName -split ' ')[3] + ' ' + ($ .BaseName -拆分 ' ')[4] + $_.Extension ) $i++ }

This gives me most of what I need, but not the additional first 7 characters:这给了我大部分我需要的东西,但不是额外的前 7 个字符:

8675309_00001_2022_FileName1_ExtraSuff1_Extrastuff2 and some more stuff_012345.html 8675309_00001_2022_FileName1_ExtraSuff1_Extrastuff2 和其他一些东西_012345.html

Ho can I tweak this script to bring in the initial characters?我可以调整这个脚本以引入初始字符吗?

Since your file names seem to have a structure or a unique character you can split them on you could use something like this:由于您的文件名似乎具有结构或独特的字符,您可以将它们拆分,您可以使用以下内容:

$i = 1 
Get-ChildItem -Filter *.html | 
ForEach-Object{
    $SplitName = $_.BaseName -split '_'
    $NewName = ((@($SplitName[0]) * 2) -join '_') + '_' + ('{0:D5}' -f $i) + '_2022' + ($SplitName[1..($SplitName.Length -1)] -join '_') + $_.Extension 
    Rename-Item -Path $_.FullName -NewName $NewName
    $i++
}

I'm curious: why do you need the same sequence of numbers twice?我很好奇:为什么你需要两次相同的数字序列?

This worked perfectly!这非常有效! Thank you for the help, Olaf.谢谢你的帮助,奥拉夫。

In terms of the multiples, it was as a result of the file being used as a read into a batch upload.就倍数而言,这是由于文件被用作读取批量上传的结果。 The original name wasn't able to be used with our utility.原始名称无法与我们的实用程序一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM