我有一个包含许多文件夹的目录。
Root Folder
>directory
>subdirectory
>img
image1.gif
>subdirectory2
>img
image1.gif
>directory2
>img
image1.gif
...
我希望每个图像都有其父文件夹,并带有“_”分隔符 - 直到根文件夹,而不预先添加“img”文件夹。
因此,在我们的例子中,它将我们的图像名称更改为:
Root Folder
>directory
>subdirectory
>img
directory_subdirectory_image1.gif
>subdirectory2
>img
directory_subdirectory2_image1.gif
>directory2
>img
directory2_image1.gif
然后,如果可能的话,如果我可以将所有图像复制到一个重命名的文件夹,那将更为可取。
我尝试使用Renamer无效(不允许使用if语句,因此无法跳过图像):
我正在尝试编写一个批处理脚本来完成此任务,但遇到一些麻烦,特别是IF和获取所有目录/子目录。
@echo off
pushd "Folder"
for /d %%D in (*) do (
pushd "%%D"
for /r %%F in (*) do (
for %%P in ("%%F\..") do (
ren "%%F" "%%~nxP_%%~nxF"
)
)
popd
)
popd
有人可以帮我解决这个问题吗?
由于
答案 0 :(得分:3)
PowerShell答案。它不是对语言的有效使用,但我想呈现易于阅读的内容。将$rootPath
更改为您问题中Root Folder
的路径。
$rootPath = "f:\temp"
Get-ChildItem -Path $rootPath -Filter *.gif -Recurse | ForEach-Object{
$newnamePrefix = $_.DirectoryName -replace [regex]::escape("$rootPath\") -replace "\\","_"
$newName = $newnamePrefix + "_" + $_.Name
Rename-Item $_.FullName -NewName $newName
}
此代码未经测试,因此请尝试复制您的数据。使用文件的目录名来构建$newnamePrefix
,然后将其添加到当前名称。再次,这可以更有效和简化,但它应该让你知道你可以做什么。
处理动作的较短
这是上面发生的缩短版本,它会将所有文件移动到另一个目录中,并省略新名称的img
部分
$rootPath = "f:\temp"
$newPath = "F:\newdirectory"
Get-ChildItem -Path $rootPath -Filter *.gif -Recurse |
Rename-Item -NewName {$_.FullName -replace "$([regex]::Escape("$RootPath"))\\(.*?)\\img(\\.*?\.gif)", '$1$2' -replace "\\","_"} -PassThru |
Move-Item -Destination $newPath
同样,这没有经过测试。
答案 1 :(得分:0)
以下是此任务的注释批处理解决方案:
@echo off
setlocal EnableDelayedExpansion
set "RootFolder=C:\Temp\Test\"
set "ListFile=%TEMP%\FilesList.tmp"
rem Get list of all files in all subdirectories.
dir /A-D /B /ON /S "%RootFolder%">"%ListFile%" 2>nul
if errorlevel 1 goto CleanUp
rem For each file in list file do the file rename.
for /F "usebackq delims=" %%F in ("%ListFile%") do call :RenameFile "%%F"
:CleanUp
del "%ListFile%"
goto :EOF
:RenameFile
rem The list file contains each file name with full path.
set "FileNameWithPath=%~1"
rem Get full path to file.
set "FilePath=%~dp1"
rem Remove the backslash at end of path.
set "FilePath=%FilePath:~0,-1%"
rem Get name of folder containing the file.
for /F "delims=" %%D in ("%FilePath%") do set "ImageFolder=%%~nD"
rem Remove the root folder path from file name with path.
set "NewFileName=!FileNameWithPath:%RootFolder%=!"
rem Remove the folder containing the file.
set "NewFileName=!NewFileName:\%ImageFolder%\=_!"
rem Replace all backslashes by underscores.
set "NewFileName=%NewFileName:\=_%"
rem Execute the file renaming operation.
ren "%FileNameWithPath%" "%NewFileName%"
goto :EOF
分配给顶部的本地环境变量 RootFolder 的值必须适应您的根文件夹路径。最后的反斜杠很重要,否则所有文件名都会在重命名操作后以下划线开头。
注意:强>
如果包含图像文件的文件夹名称在路径中存在两次,即结果将是错误的
directory\img\subdirectory\img\image1.gif
结果
directory_subdirectory_image1.gif
而不是
directory_img_subdirectory_image1.gif