Satendra Varma
Satendra Varma

Reputation: 37

Redirecting output to a text file does not work in Batch

I am trying to delete lines that contain certain words. Using the following code

for /r %%f in (*%fileExtension%) do (
    >"%%f" (
        type "%%f" | findstr /v /c:"%value%"
    )
)

After I run this, the text file ends up being empty. If instead of >, I use >>, it will append to the file, but > does not work.

Can any body suggest what could be the issue here?

Upvotes: 1

Views: 323

Answers (2)

Io-oI
Io-oI

Reputation: 2565


There is no need to create a temporary file for each extension that you will use as a filename if you can duplicate the for loop and get a single file at each extension in this processing ...


@echo off

set "value=string" && set "fileExtension=xml,dat,log,txt,htm,bat,cmd,scr,any"
for /d /r %%E in (%fileExtension%)do >nul (for /f "tokens=*delims=" %%f in ('
if exist "%%~dpE*.%%~nE" type "%%~dpE*.%%~nE"^|findstr /vlc:"%value%"') do (
echo="%%~f">>"%~dp0%%~nE")) &rem to save %%f in each folder: %%E %%~dpE%%~nE

Obs.: 1) For to 1st check if the file extension exist befor type %%E:

  • if exist "%%~dpE*.%%~nE" type "%%~dpE*.%%~nE"^|findstr /vlc:"%value%"

Obs.: 2) For apply recursively in every sub-folder:

  • for /d /r

Obs.: 3) By executing this command below to get more info about command for, findstr and set:

  • >"%temp%\help_cmds.txt" (for /? & set /? & findstr /?) & "%temp%\help_cmds.txt"

Upvotes: 2

R1cky
R1cky

Reputation: 753

I think you cannot rewrite your source while reading it. I'm pretty sure that it looks like a command but on background it's still reading line by line and right away you're rewriting the file content, thus removing what it suppose to read and leaving the output thus only blank. Try to store it into some temporary file and then put it back to the original place.

Something like this should do the trick for you:

for /r %%f in (*%fileExtension%) do (
    type "%%f" | findstr /v /c:"%value%" > tmp
    type tmp > "%%f"
)
del tmp

Upvotes: 1

Related Questions