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

Jerold Schulman

August 16, 2006

1 Min Read
ITPro Today logo in a gray background | ITPro Today

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 offif {%1}=={} @echo Syntax: ReadReverse FileName&goto :EOFif not exist %1 @echo Syntax: ReadReverse - %1 does not exist.&goto :EOFsetlocal EnableDelayedExpansionset input=%1set output="%TEMP%ReadReverse_%RANDOM%.TMP"if exist %output% del /q %output%if exist "%TEMP%ReadReverse.vbs" goto :[email protected] objArguments, fso, readfile, contents, writefile, seq>"%TEMP%ReadReverse.vbs"@echo.Set objArguments = Wscript.Arguments>>"%TEMP%ReadReverse.vbs"@echo.input=objArguments(0)>>"%TEMP%ReadReverse.vbs"@echo.output=objArguments(1)>>"%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"@echo.readfile.close>>"%TEMP%ReadReverse.vbs"@echo.writefile.close>>"%TEMP%ReadReverse.vbs":doitcscript //nologo "%TEMP%ReadReverse.vbs" %input% %output%for /f "Tokens=1* Delims=," %%a in ('type %output%^|Sort /Reverse') do ( @echo %%b)del /q %output%endlocal


Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like