Q. How can I process a text file in reverse order?

I have scripted ReadReverse.bat to return the records in a text file in reverse order, from last to first.

The syntax for using ReadReverse.bat is:

for /f "Tokens=*" %%a in ('ReadReverse InputFile') do (
 @echo %%a
Where InputFile is the file name you wish to read in reverse order. %%a contains each returned record.

ReadReverse.bat contains:

@echo off
if \{%1\}==\{\} @echo Syntax: ReadReverse FileName&goto :EOF
if not exist %1 @echo Syntax: ReadReverse - %1 does not exist.&goto :EOF
setlocal EnableDelayedExpansion
set input=%1
set output="%TEMP%\ReadReverse_%RANDOM%.TMP"
if exist %output% del /q %output%
if exist "%TEMP%\ReadReverse.vbs" goto :doit
@echo.Dim objArguments, fso, readfile, contents, writefile, seq>"%TEMP%\ReadReverse.vbs"
@echo.Set objArguments = Wscript.Arguments>>"%TEMP%\ReadReverse.vbs"
@echo.set fso = CreateObject("Scripting.FileSystemObject")>>"%TEMP%\ReadReverse.vbs"
@echo.set readfile = fso.OpenTextFile(input, 1, false)>>"%TEMP%\ReadReverse.vbs"
@echo.set writefile = fso.CreateTextFile(output, 2)>>"%TEMP%\ReadReverse.vbs"
@echo.seq = 999999999>>"%TEMP%\ReadReverse.vbs"
@echo.Do until readfile.AtEndOfStream = True>>"%TEMP%\ReadReverse.vbs"
@echo.     contents = readfile.ReadLine>>"%TEMP%\ReadReverse.vbs"
@echo.     seq = seq + 1 >>"%TEMP%\ReadReverse.vbs"
@echo.     writefile.writeLine seq ^& "," ^& contents>>"%TEMP%\ReadReverse.vbs"
@echo.     loop>>"%TEMP%\ReadReverse.vbs"
cscript //nologo "%TEMP%\ReadReverse.vbs" %input% %output%
for /f "Tokens=1* Delims=," %%a in ('type %output%^|Sort /Reverse') do (
 @echo %%b
del /q %output%

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.