Kairan
Kairan

Reputation: 5542

Remove line of text from a batch file

Ive scoured for days online and have not found what I am looking for.

I am reading in a file line by line, grabbing the first token which is a filename, then running that file. After running the file I would move it to an archive folder and delete the line of text from the file before reading the next line.

I need to remove that line of text AFTER the file is run but cannot figure out how to do that

@ECHO OFF
REM Get time date in special format
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c%%a%%b)
For /f "tokens=1-2 delims=/: " %%a in ("%TIME%") do (set mytime=%%a%%b)

REM Loop through each line
FOR /F "tokens=1-3 delims=, " %%i IN (./ready/input.txt) DO (

    REM>output.txt

    REM Run the file
        call .\ready\%%i || goto :error

    REM Move the file to archive folder
    move .\ready\%%i .\archive\%mydate%_%mytime%_%%j_%%k_%%i

    REM ***Remove the current line of text from input.txt ****

)
goto :EOF

:error
echo Failed with error #%errorlevel%.
exit /b %errorlevel%

Edit: More info. What I am trying to do, is track the files that did not run... so there might be 6 lines of files, it might read line 1 run the file, read line 2 run the file, then cannot find file 3 so it exits... i need to be able to output the last 4 lines

Upvotes: 0

Views: 1488

Answers (1)

Magoo
Magoo

Reputation: 80033

@ECHO OFF
REM Get time date in special format
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c%%a%%b)
For /f "tokens=1-2 delims=/: " %%a in ("%TIME%") do (set mytime=%%a%%b)

REM Loop through each line
set "errorfound="
del newfile.txt >nul 2>nul
FOR /F "tokens=1-3 delims=, " %%i IN (./ready/input.txt) DO (

 REM YOU DO REALISE THIS NEXT LINE WILL RE-CREATE THE FILE EACH ITERATION DON'T YOU?
 REM>output.txt

 REM Run the file
 if not defined errorfound (
  call .\ready\%%i
  if errorlevel 1 (
   REM PRESUME ERRORLEVEL1+=fail
   set errorfound=Y
   ) else (
    REM Move the file to archive folder
    move .\ready\%%i .\archive\%mydate%_%mytime%_%%j_%%k_%%i
  )
 )
 if defined errorfound >>newfile.txt echo %%i %%j %%k
)

if defined errorfound echo error found-unprocessed lines in newfile.txt
goto :EOF

Presuming you want to stop on the first error, the above should work.

errorfound is set once er, an error is found. if defined works on the current value of the variable, so after the first error is found, it reproduces the significant portions of the input data lines to a new file.

Upvotes: 1

Related Questions