批处理脚本将父文件夹名称的一部分添加到里面的pdf

Batch script to add part of parent folder name to pdfs inside

我有一个 windows 目录,其中包含名称如下的文件夹:

Lot 1
Lot 2
Lot 5
Lot A
Block A
Block C

这些文件夹中的每一个都包含 PDF 测量图。文件的名称无关紧要。我的目标是在 ONLY LOT FOLDERS 中的每个 PDF 前面加上其父文件夹名称的编辑版本。我不想将前缀 Lot 1_ 添加到文件夹 Lot 1 中的文件的文件名中,而是想将 L1_ 添加到文件名中。

目前,我有一个批处理文件,它将提示中输入的任何前缀添加到当前文件夹中的所有 PDF。这意味着我必须进入每个文件夹和 运行 批处理脚本。这很乏味,因为我有成千上万的人要处理。

代码如下所示:

Set /p prefix="Enter Prefix to add to file names: "
FOR /f "delims=" %%F IN ('DIR /a-d /b *.PDF') DO (RENAME "%%F" %prefix%_"%%F")

我一直在尝试创建一个批处理文件来遍历名称中包含 Lot 和 space 的所有文件夹,到目前为止我所能做的就是使用 for 循环来获取所有 Lot任意编号的名称并将它们输出到文本文件。

代码如下所示:

for /f "delims=" %%F in ('dir /A:D /b Lot*') do echo %%F >> folders.txt

然后我得到文本文件:

Lot 1
Lot 2
Lot 5
Lot A

我也可以只输出文件夹名称的数字部分。该代码:

for /f "tokens=2" %%F in ('dir /A:D /b Lot*') do echo %%F >> folders2.txt

然后我得到文本文件:

1
2
5
A

我觉得我真的很接近最后一个,但我试图做的不是回显 folders2.txt 我想进入另一个 for 循环,我将在 [=22] 中重命名每个文件=] 并添加前缀 L%%F 和文件名的其余部分。

有人有什么想法吗?

另一个论坛的人给了我这个有效但每个 Lot 文件夹中的第一个文件被命名两次...我不明白为什么。

另一个论坛上有人提供了以下有效但每个 Lot 文件夹中的第一个文件被标记为 L_ 两次,我不知道为什么......

@echo off & setlocal
for /f "tokens=*" %%a in ('dir /b /ad lot*') do (
for %%b in ("%%a"\*.pdf) do call :xx "%%~dpb" "%%~nxb"
)
goto :eof

:xx
set z=%~1
set z=%z:~0,-1%
for %%c in ("%z%") do set k=%%~nc
set k=%k:lot =L%
echo ren %1%2 %k%_%2
ren %1%2 %k%_%2

这个怎么样:

@echo off
rem // Switch to the target directory:
pushd "D:\Target" && (
    rem /* Loop through all directories whose names begin with `Lot` + SPACE;
    rem    the `findstr` portion further filters the directory names so that
    rem    they must begin with `Lot` + SPACE + a character other than SPACE;
    rem    everything starting at a potential following SPACE is ignored: */
    for /F "tokens=1-2" %%C in ('
        2^> nul dir /B /A:D "Lot *" ^| findstr /I "^Lot [^ ]"
    ') do (
        rem /* Loop through all `*.pdf` files in the currently iterated directory;
        rem    the `findstr` portion further filters the file names so that they must
        rem    not equal `L` + the second token from the outer loop + something containing
        rem    a `_` + `.pdf`, because such files are considered as already renamed: */
        for /F "delims=" %%F in ('
            2^> nul dir /B /A:-D "%%~C %%~D\*.pdf" ^| findstr /I /V "^L%%~D_.*\.pdf$"
        ') do (
            rem // Check whether target file name already exists:
            if exist "%%~C %%~D\L%%~D_%%F" (
                rem // Collision, hence skip file and return error message:
                >&2 echo Collision: cannot rename "%%~C %%~D\%%F" to "L%%~D_%%F"!
            ) else (
                rem // No collision, so actually rename the currently iterated file:
                ECHO ren "%%~C %%~D\%%F" "L%%~D_%%F"
            )
        )
    )
    rem // Return to original working directory:
    popd
)

测试输出正确后,ren 命令中删除大写字母 ECHO!