Win bat file: How to get the result of FIND into a new variable?
-
12-11-2019 - |
Question
The pdftk tool "dump_data" function can be used to deliver meta information about a pdf, including the number of pages. The following command...
pdftk test.pdf dump_data | find "NumberOfPages"
...outputs the full data dump line, for example:
"Number of pages: 32"
How can I get the count value (32 in the above case) into a new variable for further processing in the bat file?
Solution
If the format of the line is fixed and matches the one you've shown, you could try something like this:
@ECHO OFF
>testfile ECHO Number of pages: 32
FOR /F "delims=: tokens=2" %%A IN ('TYPE testfile ^| FIND "Number of pages"') DO SET /A pagenum=%%A
ECHO %pagenum%
Outputs:
32
Naturally, >testfile ECHO ...
line is just for testing purposes, and the TYPE testfile
part of the FOR
loop should be replaced by your pdftk test.pdf dump_data
.
OTHER TIPS
Try this:
FOR /F "usebackq delims=" %%v IN (`pdftk test.pdf dump_data ^| find "Number of pages"`) DO (
FOR /F "delims=: tokens=1,2" %%i IN ("%%v") DO set NBPAGES=%%j
)
Note that you have to use two %
in front of every variables in the above example if you are using it in a batch file. If you are running it directly from the console, use only one %
.