问题描述
我正在尝试合并大量具有相似数字的 pdf 文件
例如“NR 01234567_1.pdf” “NR 01234567_2.pdf” 等等 在一个文件夹中,该文件夹包含数千个需要按文件名合并的类似文件页面 例如“NR 01234567.pdf”
我使用下面的脚本成功地使用了这种方法,所有文件名中没有空格的文件(感谢本论坛上一些非常有帮助的人),但它不能使用名称中的空格。
有人能帮我解决这个问题吗?
@echo off
setlocal EnableDelayedExpansion
rem Initialize (delete) "lastFile" and "fileList" variables
set "lastFile="
set "fileList="
rem Next line get the output of a "dir /B" command,that show file names *only*
rem "for /F" command execute the dir,get the output and divide each line in two "tokens" ("%%a" and "%%b")
rem with the first part before the "_" in "%%a" and the *rest* (including further "_") in "%%b"
for /F "tokens=1* delims=_" %%a in ('dir /B *.*') do (
rem If the base file name changed...
if "%%a" neq "!lastFile!" (
rem Process previous file list;
rem this "if" is just to avoid process the empty list the first time
if defined fileList (
pdftk !fileList! output !lastFile!.pdf
)
rem Reinitialize the new list
set "lastFile=%%a"
set "fileList=%%a_%%b"
) else (
rem Append this file to current list
set "fileList=!fileList! %%a_%%b"
)
)
rem Process the last list
pdftk !fileList! output !lastFile!.pdf
解决方法
set "fileList="%%a_%%b""
) else (
rem Append this file to current list
set "fileList=!fileList! "%%a_%%b""
和
pdftk !fileList! output "!lastFile!.pdf"
(两个地方)
[未尝试 - 我没有 pdftk
(AFAIK)]
这个想法是将 filelist
构建为 "xy abcd" "xy defg"
- 故意包含引号 = 以便 pdftk
将 "xy abcd" "xy defg"
视为其要合并的文件列表和"xy doom"
作为目标文件(是的 - 我随意使用了名称。正如“新数学”所描述的那样,"it's the idea that counts")
我认为可能有一种更简单的方法来完成这项任务。我记得 pdftk.exe
有一个 cat
选项,可以使用通配符/glob。因此,您可以使用该选项,而不是创建文件列表。
这里有一个例子,(请先在第 pdftk.exe
行更改 3
的位置),然后将保存 PDF 文件的目录作为当前目录运行它:
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "tkPDF=P:\ath\To\pdftk.exe"
Set "lastPreName="
For /F "EOL=_ Tokens=*" %%G In ('Dir "*_*.pdf" /B /A:-D /O:N 2^> NUL
^| "%SystemRoot%\System32\findstr.exe" /I /R "^.[^_]*_[^_]*.pdf$"'
) Do For /F "Tokens=1,* Delims=_" %%H In ("%%~nG") Do (
SetLocal EnableDelayedExpansion
If /I Not "!lastPreName!" == "%%~H" (
Echo="%tkPDF%" "%%~H_*%%~xG" cat output "%%~H%%~xG")
EndLocal
Set "lastPreName=%%~H")
Pause
如果您对输出感到满意,目前只显示将运行的命令,请从第 Echo=
行中删除 10
,并在第 {{ 行中删除可选的 Pause
1}}