首页 > 解决方案 > 根据内容(关键字)复制pdf文件

问题描述

我正在尝试创建 cmd 代码来扫描并复制包含特定关键字的 pdf 文件,并将副本保存到单独的文件夹中。下面是我的代码,但它不起作用

@echo off

set "source=C:\instructions"
set "target=C:\instructions\cafe"
set "string=cafe"

set "logfile=logs.txt"

call :main >> "%logfile%"

pause

goto :EOF

:main

for /r "%source%\%dt%" %%a in ("*.pdf") do (
    find /c /i "%string%" "%%~a" 1>&2
    if not errorlevel 1 (
        set /p "out=%%~a / " <nul
        if exist "%target%\%%~nxa" (
            echo:Already exists
        ) ELSE (
            copy "%%~a" "%target%"
            if errorlevel 1 (
                echo:Failed
            ) ELSE (
                echo:Success
            )
        )
    )
)

goto :EOF

有人可以帮我吗?

标签: windowsbatch-filecmd

解决方案


Find 仅适用于编码 pdf 的纯文本内容,因此如果关键字被加密,则可能找不到它们。为了解决这个限制,windows 有内容索引,对于 pdf,它需要一个 iFilter,它通常由默认的 pdf 阅读器提供(避免添加多个)。如果您没有从 Adob​​e、SumatraPDF、Tracker PDF-Xchange 或 Foxit Reader 安装。您会在https://www.pdflib.com/download/tet-pdf-ifilter/找到一个不错的(免费但有限的)

假设文本是可检测的

您的主要问题是通常需要setlocal enabledelayedexpansion其他一些(例如如果目标文件夹不存在),因此我建议您删除消息的隐藏但已纠正主要问题。

@echo off

REM use delayed expansion for testing !errorlevel!
setlocal enabledelayedexpansion

set "source=C:\instructions"
set "target=C:\instructions\cafe"
set "string=cafe"
set "logfile=logs.txt"

call :main >> "%logfile%"

pause

goto :EOF

:main
REM &dt% will default to nothing ? is it needed?

for /r "%source%\%dt%" %%a in ("*.pdf") do (
    find /c /i "%string%" "%%~a" 1>&2
REM your test here needs changing to this
    if !errorlevel! == 0 (
        set /p "out=%%~a / " <nul
        if exist "%target%\%%~nxa" (
            echo:Already exists
        ) ELSE (
            copy "%%~a" "%target%"
REM your test here needs changing to this
            if !errorlevel! == 1 (
                echo:Failed
            ) ELSE (
                echo:Success
            )
        )
    )
)

goto :EOF

推荐阅读