Wednesday, July 1, 2009

How to reverse contents of a file in windows

I recently needed to mimic the linux functionality of being able to reverse the contents of any file, on windows. After playing with a few options, I found vb-scripting to be the least painful way to do this. See below for details:

Step 1:
Save the script below as a .vbs file for example ReverseStream.vbs

' ------- BEGIN CALLOUT A -------Dim Stack: Set Stack = CreateObject("System.Collections.Stack")' ------- END CALLOUT A -------
' ------- BEGIN CALLOUT B -------Do While Not WScript.StdIn.AtEndofStream Stack.Push WScript.StdIn.ReadLineLoop' ------- END CALLOUT B -------
' ------- BEGIN CALLOUT C -------WScript.StdOut.WriteLine Join(Stack.ToArray, vbCrLf)' ------- END CALLOUT C -------

Step 2:
To run the script use the following command on the cmd shell

c:\>cscript c:\ReverseStream.vbs c:\Reversefile.xml