Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows batch script help for checking last line of the file

I have a few hundred files,most of which contains 'exit' at the end(the end line).Not all of the files have this 'exit' at the end.How can I check the content of last line of the files and then remove it if it's 'exit'?

like image 623
Rajat Saxena Avatar asked Dec 12 '22 14:12

Rajat Saxena


1 Answers

@echo off
setlocal EnableDelayedExpansion

rem "I have a few hundred files"
for %%a in (*.*) do (
   rem "most of which contains 'exit' at the end line."
   set "lastLine="
   (for /F "usebackq delims=" %%b in ("%%a") do (
      if not defined lastLine (
         set "lastLine=%%b"
      ) else (
         echo(!lastLine!
         set "lastLine=%%b"
      )
   )) > "%%~Na.tmp"
   rem "Not all of the files have this 'exit' at the end."
   rem "How can I check the content of last line of the files"
   if "!lastLine!" equ "exit" (
      rem "and then remove it if it's 'exit'?"
      move /Y "%%~Na.tmp" "%%a"
   ) else (
      del "%%~Na.tmp"
   )
)
like image 55
Aacini Avatar answered Jan 03 '23 17:01

Aacini