Question

I need a batch file that will check the amount of lines contained in files within a specified folder that have a .txt extension and delete any of those files that have less than 3 lines.

So far my code prints the total amount of lines within each .txt file within the specified folder. The problem is that I can't figure out how to capture that information into a variable:

@echo off
for %%A in ("D:\test\*.txt") do (
    findstr /R /N "^" %%A | find /C ":"
)

My attempts to modify this code to perform what I need it to has failed:

@echo off
set count=0
for %%A in ("D:\test\*.txt") do (
    set /a count=findstr /R /N "^" %%A | find /C ":"
    if %count% LSS 3 del %%A
)

Please could someone offer some advice or a solution to this issue.

Any help will be greatly appreciated.

Was it helpful?

Solution

This works here:

@echo off
for %%a in ("d:\test\*.txt") do for /f %%b in ('find /c /v "" ^< "%%a" ') do if %%b LSS 3 del "%%a"

OTHER TIPS

You can use FIND /C to quickly count the number of lines in all *.txt files, and pipe that result to FINDSTR to filter out only lines that end with a count of 0, 1, or 2. The last moderately tricky bit is using a pair of FOR /F loops to parse the result to give a list of file names only, stripping out the leading ---------- as well as everything after the colon.

@echo off
pushd "D:\test\"
for /f "tokens=1*" %%A in (
  'find /c /v "" *.txt^|findstr /rc:" [012]$"'
) do for /f "delims=:" %%F in ("%%B") do del "%%F"
popd

Just get the value in the for variable and test it

rem Enumerate the files
for %%f in (*.txt) do (
    rem Count lines in file not containing some inexistent text, 
    rem so we get the number of lines in file
    for /f %%c in ('type "%%f" ^| find /v /c "TeXtNoTiNfIlEs"') do (
        rem if count is less than 3, delete file
        if %%c lss 3 del %%f
    )
)
for /r "D:\test" %%a in (*.txt) do (
    set "smallfile=true"
    for /f "delims=:" %%b in ('findstr /n "^" "%%~a"') do if %%b geq 3 set "smallfile="
    if defined smallfile del "%%~a"
)

Try this instead (it will do it in the subfolders as well):

@echo off
setlocal enabledelayedexpansion
for /r "D:\test\" %%a in (*.txt) do (
set count=0
for /f "usebackq" %%b in ("%%~a") do (
set count+=1
)
if !count! lss 3 (
del "%%a"
Echo Deleting %%a
))

And I think that should work, (If none of the lines start with ;).

Hope this helped,

Mona

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top