Changing For Loop to Search for Specific Files

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Galius
Posts: 1
Joined: 30 Nov 2017 21:00

Changing For Loop to Search for Specific Files

#1 Post by Galius » 30 Nov 2017 21:04

I have a script that when used with the format NAME_KM_1, NAME_KM_2, NAME_KM_3, etc. It will combine all files with _KM_ in the filename into a pdf using pdftk.

In my scenario my file names all start with something like this Q1111_CONFIRM, Q1111_ORDER, Q2222_CONFIRM, Q2222_ORDER. How would I modify this one to combine the order/confirm matching the Qnumber? I tried a few different things with no success.

I know I need to change something in this line:

for /F "tokens=1* delims=_" %%a in ('dir /B *_KM_*.*') do (

but I cannot work out what to change it to in order for it to work in my scenario. Would someone be able to help me?

Code: Select all

@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 *_KM_*.*') 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"
 
)
 
)
Last edited by Squashman on 30 Nov 2017 22:39, edited 1 time in total.
Reason: MOD EDIT: Fixed code formatting.

Squashman
Expert
Posts: 4486
Joined: 23 Dec 2011 13:59

Re: Changing For Loop to Search for Specific Files

#2 Post by Squashman » 30 Nov 2017 22:50

Saw your post on SO as well.

I don't know the syntax for PDFTK, but I think this should work.

Code: Select all

@echo off

FOR /F "TOKENS=1,2 delims=_" %%G IN ('dir /a-d /b Q*_ORDER.pdf') DO (
	IF EXIST "%%~G_CONFIRM.pdf" pdftk "%%~G_ORDER.PDF" "%%~G_CONFIRM.PDF" output "%%~G.pdf"
)

Post Reply