Search code examples
batch-filefor-loopif-statementfindstrblat

Using loops to rename filenames with batch script


I have a a folder with the files: File1.txt and File2.txt

The contents of file1.txt are:

"DTS053C0 RUN DATE 10/01/11 DATATRAK SYSTEM PAGE 001
RUN TIME 13:35:08
INPUT PROGRAM TRANSMISSION STATUS REPORT
STATUS - INPUT RECEIVED BY DTCC'S DATATRAK SYSTEM
DETAIL RECORDS RECEIVED 0
HEADER RECORD RECEIVED
HDR.SSYSID.E00.CORIG.SSUBOMMDDYYYY HEADERFILEDESCRIPTION N001 *
REJECTED
NO MATCH ON EXPECTED MASTER FOR HEADER" 

Contents of file2.txt are:

"The confirm file received from DTCC will be in the following format:
DTS053C0 RUN DATE 10/01/11 DATATRAK SYSTEM PAGE 001
RUN TIME 12:53:32
INPUT PROGRAM TRANSMISSION STATUS REPORT
STATUS - INPUT RECEIVED BY DTCC'S DATATRAK SYSTEM
DETAIL RECORDS RECEIVED 22
HEADER RECORD RECEIVED
HDR.SSYSID.E00.CORIG.SSUBOMMDDYYYY HEADERFILEDESCRIPTION N001 *
ACCEPTED
Example"

I am looking for a batch script to scan through the contents of these 2 files separately and identify the files which contain the word "REJECTED" and then send an email to my email-id like a notification saying "this file has been rejected, kindly check".

  • I am using blat to send emails as notifications *

Solution

  • To wrap @Stephans suggestion into a batch:

    • Findstr /M reports only file names which had a match on REJECTED,
    • The for /f processes this output and the set gathers this in the variable Found. The first entry produces a leading comma.
    • When finally passing this variable content as an argument to the subroutine :Blat this first comma is removed by substring %Found:~1% from 2nd pos (zero based)
    • In the sub you can use %* = (all passed arguments) to have it as mail subject or body for your blat routine.

    :: Q:\Test\2018\06\14\SO_50858355.cmd
    @Echo off & Setlocal EnableDelayedExpansion
    Set "Search=REJECTED"
    Set "Files=file?.txt"
    Set "Found="
    for /f "delims=" %%A in ('
      findstr /m /i "%Search%" %Files%
    ') Do set "Found=!Found!,%%A"
    If Defined Found (
        Call :Blat %Found:~1%
    ) Else (
        Echo No files "%Files%" containing "%Search%" found
    )
    Pause
    Goto :Eof
    
    :Blat
    Echo found Rejected in %1
    If "%2" neq "" (shift & goto :Blat)
    

    Sample output:

    > SO_50858355.cmd
    Yourblatcommand found Rejected in file1.txt
    

    new sample output:

    > SO_50858355.cmd
    found Rejected in file3.txt
    found Rejected in file1.txt
    

    The batch file as is searches only in the current folder and with the wildcard file?.txt so you have to adapt the variables to fit your needs or first set anotther working dir.