这个问题可能听起来很混乱,但我真正需要的是能够使用字符串数组更改文件名。使用txt文件中的字符串重命名文件
例如:
文件1包含: abc1234cd.jpg abc2543ac.jpg ...
文件2包含(阵列/参考)
1234c 2543a ...
abc1234cd.jpg的新文件名现在应该是1234c.jpg等等。
这是可能的PowerShell或任何其他语言做?
谢谢,
这个问题可能听起来很混乱,但我真正需要的是能够使用字符串数组更改文件名。使用txt文件中的字符串重命名文件
例如:
文件1包含: abc1234cd.jpg abc2543ac.jpg ...
文件2包含(阵列/参考)
1234c 2543a ...
abc1234cd.jpg的新文件名现在应该是1234c.jpg等等。
这是可能的PowerShell或任何其他语言做?
谢谢,
这应该这样做,假设文件有一对一的匹配。
# Get contents of file 1
$File1 = Get-Content -Path $PSScriptRoot\File1.txt;
# Get contents of file 2
$File2 = Get-Content -Path $PSScriptRoot\File2.txt;
# Iterate over each item in $File1
foreach ($Item in $File1) {
$FileList = Get-ChildItem -Path "c:\test\$Item*.jpg";
foreach ($File in $FileList) {
# Determine file's new name, based on corresponding value in File2
$NewName = $File.Name -replace $Item, $File2[$File1.IndexOf($Item)];
Write-Host -Object ('Old name: {0}, new name: {1}' -f $Item, $NewName);
}
}
嗨特雷弗,我想知道是否有增加重复。 EX:abc1234cd.jpg和abc1234cd2.jpg(原始文件)变成(1234c和1234c-1) – user3225168
嗯,你必须做一些模式匹配来实现这一点。你可以在名称的公共部分做一个简单的正则表达式替换:'abc1234cd'。 –
用[未经测试]代码更新了答案。 –
无数小时后,我终于得到了代码工作。
$dir = 'file.txt'
$backup = 'C:\Users\all users\Desktop\backup'
$file = 'file2.txt'
$files = Import-Csv -Header Name -Path $file
foreach ($line in $files){
$linefiles = Get-ChildItem $dir | where {$_.BaseName.Contains($line.Name)}
$count = 0
foreach ($linefile in $linefiles) {
#do stuff to each file here
$name = $linefile.BaseName
$extension = $linefile.Extension
$newName = $line.Name
Copy-Item -Path "$dir\$linefile" -Destination "$backup\$linefile"
if ($count -gt 0){
Rename-Item -NewName "$newName-$count$extension" -Path "$dir\$linefile"}
else{
Rename-Item -NewName "$newName$extension" -Path "$dir\$linefile"}
$count++}
}
这两个列表是否可以相互关联? 1234c只会引用文件1中的单个记录(即abc1234cd.jpg)。有许多方法可以加入这两个对象。人们编写了自定义的Join-Object函数,您可能能够重现。但这取决于两个阵列能够匹配。 – websch01ar
实际上可能会出现这种情况,abc1234cd.jpg也可以是abc1234cd2.jpg。我需要将它们重命名为1234c.jpg和1234c-1。 1234c-1.jpg作为增量,因为它包含1234c – user3225168