Solved Delete the file if it has only one line

Microsoft Windows server 2003 enterprise
November 28, 2016 at 19:40:10
Specs: Win 7, intel

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 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.


See More: Delete the file if it has only one line

Report •

November 28, 2016 at 22:40:02
::====== script starts here ===============
:: delete txt files which have only one line
:: onlyone.bat 2016-11-29 13:32:46.25
@echo off & setLocal enableDELAYedeXpansioN

dir/b *.txt > myfile

for /f "tokens=* delims= " %%a in (myfile) do (
call :sub1 %%a
if !N! equ 1 echo del %%a
goto :eof

set/a N=0
for /f "tokens=* delims= " %%i in (%1) do (
if !N! equ 2 goto :eof
set/a N+=1
goto :eof
::====== script ends here =================


M2 Get custom script or take private lessons

Report •

November 29, 2016 at 03:03:25
✔ Best Answer
Using a different approach, avoiding temporary files as well as handling filenames with spaces.
@echo off
setlocal enabledelayedexpansion
set path=C:\tmp
for /f "tokens=*" %%A in ('dir /b "!path!\*.txt"') do (
	set count=0
	call :countlines "%%A"
goto :eof
for /f "usebackq tokens=*" %%Z in ("%~1") do (
	if !count! GTR 2 (
		goto :eof
	set /a count+=1
if !count! EQU 1 (
	echo del "%~1"
goto :eof

Don't worry if plan A fails, there are 25 more letters in the alphabet ;)

message edited by RainBawZ

Report •
Related Solutions

Ask Question