在 shell 中,如何递归替换目录内容中的文件名和目录名,同时保留现有大小写?例如,一个子目录可以命名为“Test”或“test”,我希望能够分别将其替换为“Testa”或“testa”。
最佳答案
注意事项 - 小心运行,因为您可能最终会重命名大量文件,然后意识到您向文件添加了错误的字符。这里没有撤消按钮;)
好吧,如果我理解正确的话,就可以了。
带有几个 .txt 文件的文件夹结构是
C:\Folder\firstfolder
C:\Folder\fourthFolder
C:\Folder\SecondFolder
C:\Folder\Thirdfolder
C:\Folder\firstfolder\aFile.txt
C:\Folder\SecondFolder\Anotherfile.txt
C:\Folder\Thirdfolder\yetAnotherFile.txt
脚本如下。我必须将文件夹和文件分开,因为文件有扩展名,您可能不想在扩展名后添加重命名字符串。
$source="C:\Folder"
$addtoname="A"
Get-ChildItem $source -Recurse | foreach {
$location = Split-Path $_.FullName
if($_.PSIsContainer){
$name=$_.Name
Rename-Item $location"\"$name $location"\"$name$addtoname
}
else
{
$name = $_.BaseName
$ext = $_.Extension
Rename-Item $location"\"$nameext $location"\"$name$addtoname$ext
}
}
之后的结果是
C:\Folder\firstfolderA
C:\Folder\fourthFolderA
C:\Folder\SecondFolderA
C:\Folder\ThirdfolderA
C:\Folder\firstfolderA\aFileA.txt
C:\Folder\SecondFolderA\AnotherfileA.txt
C:\Folder\ThirdfolderA\yetAnotherFileA.txt
我希望这就是您想要的,我没有白白投入时间。
关于linux - 在保留大小写的同时递归替换文件和目录名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40144477/