Question

I am working on making a list of pdf files. There are 2480 pdfs in the directory. I want to put the first half in var l1 and the second in var l2.

for /r %%f in (*_*.pdf) do (
  set c=%%~nf
  set c=%c:~5,4%
  if %c% LEQ 1240 ( set l1=%l1% %%~nf.pdf )
  if %c% GEQ 1241 ( set l2=%l2% %%~nf.pdf )
)
pdftk %l1% cat output group1.pdf
pdftk %l2% cat output group2.pdf

I have tried several combinations but cant quite get it to work. The aforementioned script is the basic premiss of what I need done. I am using pdftk to merge the files.

Was it helpful?

Solution

Classic problem - %c% etc are expanded when the line is parsed, and the entire FOR loop is parsed all at once. So the value within the loop is constant - the value that existed before the loop started. (probably no value).

The fix is simple - you need delayed expansion. You can read about in the built in help for SET. Type HELP SET or SET /? from the command prompt. The important bit is about 2/3 down, starting with "Finally, support for delayed environment variable expansion has been added..."

You need to enable delayed expansion with SETLOCAL ENABLEDELAYEDEXPANSION before it can be used.

setlocal enableDelayedExpansion
for /r %%f in (*_*.pdf) do (
  set c=%%~nf
  set c=!c:~5,4!
  if !c! LEQ 1240 ( set l1=!l1! %%~nxf )
  if !c! GEQ 1241 ( set l2=!l2! %%~nxf )
)
pdftk %l1% cat output group1.pdf
pdftk %l2% cat output group2.pdf
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top