Batch script to check if the file has one line and delete

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
gaurde
Posts: 1
Joined: 28 Nov 2016 21:29

Batch script to check if the file has one line and delete

#1 Post by gaurde » 28 Nov 2016 21:35

Hi,

I am new to the forum, please help to suggest how can I achieve the below.

I am generating some .txt files in a particular directory from a datastage job (ETL tool), some times where there are no records the files are generated with header only. I tried deleting the files based on the file size but the problem is the files which are generated with header and the files which are generated with detail some time are of the same file size.

What I am trying to do is check in the directory(c:\tmp) if all the .txt files have only one line starting with CDRNO, if yes delete the files, but I am not sure how to achieve this.

Please suggest how can I write a batch script for this.

Regards,
Deepti

penpen
Expert
Posts: 2009
Joined: 23 Jun 2013 06:15
Location: Germany

Re: Batch script to check if the file has one line and delete

#2 Post by penpen » 29 Nov 2016 04:19

This "check.bat" might help you:

Code: Select all

@echo off
setlocal enableExtensions disableDelayedExpansion

for %%a in ("c:\tmp\*.txt") do (
   call :checkFile "%%~a"
   if errorlevel 1 echo(del %%~a
)
endlocal
goto :eof


:checkFile
:: %~1   name of the file to check
:: returns 0 if file contains data, else 1 (== header only).

:: if file contains more than one line: data found
for /F "tokens=2 delims=:" %%a in ('find /c /v "" "%~1"') do (
   for /F "delims= " %%b in ("%%~a") do (
      if not 1 == %%~b exit /b 0
   )
)

:: if only line does not start with "CDRNO", then line contains data
for /F %%a in ('findstr /v "^CDRNO" "%~1"') do (
   exit /b 0
)

:: header only
exit /b 1

Note:
Actually the above batch only lists the files to delete.
If the above displayed result meets your requirements, then just delete "echo(".

penpen

Post Reply