Search code examples
batch-filebatch-processingfindstr

batch script /findstr function to echo only the left of the delimiter


I want to get only the filename inside the text file containing ".PDF"

Expected output:

PP_12345.PDF 03/05/2017 - 13:56:32.18 
PP_23456.PDF 03/05/2017 - 13:56:32.18 
PE_12345.PDF 03/05/2017 - 13:56:32.30 
PE_23456.PDF 03/05/2017 - 13:56:32.30 

Information inside the test.txt

put PP_12345.pdf some text here
DOC ID 11223344555
put PP_23456.pdf some text here
oopps this is a sample
ls PP*.pdf
put PE_12345.pdf some text here
this is a sample sentence
ls PE*.pdf
put PE_23456.pdf some text here

Here is my code:

set Logtext="PP"
set Logtext1="PE"
set findfile="test.txt"

FOR  /f "TOKENS=1 DELIMS=." %%A IN ('findstr %Logtext% %findfile%') DO echo  %%A %DATE% - %TIME% >> log.txt
FOR  /f "TOKENS=1 DELIMS=." %%A IN ('findstr %Logtext1% %findfile%') DO echo  %%A %DATE% - %TIME% >> log.txt

Here is the result of log.txt:

 put PP_12345 03/05/2017 - 13:56:32.18 
 put PP_23456 03/05/2017 - 13:56:32.18 
 ls PP* 03/05/2017 - 13:56:32.18 
 put PE_12345 03/05/2017 - 13:56:32.30 
 ls PE* 03/05/2017 - 13:56:32.30 
 put PE_23456 03/05/2017 - 13:56:32.30 

Solution

  • @ECHO OFF
    SETLOCAL
    SET "sourcedir=U:\sourcedir"
    SET "filename1=%sourcedir%\q43752174.txt"
    set "Logtext=PP"
    set "Logtext1=PE"
    REM set "findfile=test.txt"
    
    FOR /f "tokens=1-3delims=. " %%a IN ('FINDSTR /L /i /c:"%logtext%_" /c:"%logtext1%_" "%filename1%"^|find /v "*"') DO IF /i "%%c"=="pdf" (
      ECHO %%b.%%c %DATE% %time%  
    )
    
    GOTO :EOF
    

    You would need to change the setting of sourcedir to suit your circumstances.

    I used a file named q43752174.txt containing your data for my testing.

    This assumes that the filenames you seek are all preceded by wordSpace and none contain "P?_" elsewhere than as starting characters


    edit : added extra "find" filter to exclude asterisks.