使用 Powershell 使用查找文件递归重命名目录 [英] Using Powershell to recursively rename directories using a lookup file
问题描述
我需要重命名很多目录及其子目录.
I need to rename a lot of directories and their sub directories.
我有一个 csv 文件,其中包含旧目录名称和所需的新名称.
I have a csv file which contains the old directory names and the required new name.
1,blah,old_name1,new_name2,wibble
2,foo,old_name2,new_name2,bar
3,john,old_name3,new_name3,paul
4,george,old_name4,new_name4,ringo
注意部分目录名是
old_name1-morestuffhere
需要重命名为
new_name1-morestuffhere
我大致知道如何在 bash 中执行此操作:
I know broadly how I'd do this in bash:
mv -r `cat file.csv | awk -F, '{print $3* $4*}'`
..但我一定会并且完全迷失在 powershell 中.
..but I'm bound to and totally lost with powershell.
这是我到目前为止所得到的.这接近吗?:
Here's what I've got so far. Is this close?:
cat .\file.csv | foreach { $oldname = $_.split(",")[2], $newname = $_.split(",")[3], move-item $oldname*, $newname*}
推荐答案
-morestuffhere"是棘手的部分.Move-Item 和 Rename-Item 上的 Path 参数(即源位置)不带通配符.但这可以用另一种方式解决.首先,您能否像这样在 CSV 文件中添加 CSV 标头:
The "-morestuffhere" is the tricky part. The Path parameters (ie source location) on Move-Item and Rename-Item don't take wildcards. But that can be solved another way. First, can you add a CSV header to your CSV file like this:
Index,F2,OldName,NewName,F5
1,blah,old_name1,new_name2,wibble
...
如果是这样,我们可以使用 PowerShell 的 Import-Csv cmdlet.现在下面看起来有点复杂,但它处理了多个 OldName-
到 NewName-
重命名的情况.
If so, we can use PowerShell's Import-Csv cmdlet. Now the following seems kind of complicated but it handles the case of multiple OldName-<differentstuffhere>
to NewName-<sameasoldnamestuffhere>
renames.
$names = Import-Csv names.csv |
Foreach {
$oldDirs=@(Get-ChildItem . -r -filter "$($_.OldName)*" |
?{$_.PSIsContainer} | %{$_.FullName})
Add-Member -in $_ NoteProperty OldDirs $oldDirs -PassThru
}
foreach ($name in $names) {
foreach ($oldDir in $name.oldDirs) {
$dir = Split-Path $oldDir -Parent
$suffix = (Split-Path $oldDir -Leaf).Substring($name.OldName.Length)
$newPath = Join-Path $dir ($name.NewName + $suffix)
Rename-Item $oldDir ($name.NewName + $suffix) -WhatIf -ea 0
}
}
这是手工解释的,所以可能会有错误.当您对结果感到满意时,删除 -Whatif.
This is hand intrepreted so there may be errors. Remove the -Whatif when you're satisfied with the results.
这篇关于使用 Powershell 使用查找文件递归重命名目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!