Windows – How to reverse text file in Windows

windows

Please help me, how reverse/sort row in text file with batch in Windows?
Example:
I have text in this format

15/04/2013-07:10:30 lalala
15/04/2013-07:10:30 Text text
15/04/2013-07:10:30 1 lala Text

15/04/2013-07:10:36 8 text lala X
15/04/2013-07:10:36 A text lala 1

17/04/2013-10:11:12 B bext lala 4
… (other rows)

and I need reversed it in this format

17/04/2013-10:11:12 B bext lala 4
15/04/2013-07:10:36 A text lala 1
15/04/2013-07:10:36 8 text lala X
15/04/2013-07:10:30 1 lala Text
15/04/2013-07:10:30 Text text
15/04/2013-07:10:30 lalala
… (other rows)

Thank You for Your help!

Best Answer

  • Maybe it's not the prettiest way, but it's just simple and works as you want.

    echo. > output.txt
    
    for /f  "delims=@" %%j in (yourfile.txt) do (
        type output.txt > tmp
        echo %%j > output.txt
        type tmp >> output.txt
    )
    
    del tmp
    

    Don't use the example above if you want to process large files. It's really time and resources consuming solution. Here you have faster version I just prepared:

    setlocal enabledelayedexpansion
    
    set I=0
    
    for /F "tokens=*" %%k in (yourfile.txt) do (
      set /A I=!I! + 1
      set LINE!I!=%%k
    )
    
    for /L %%c in (!I!,-1,1) do (
      echo !LINE%%c! >> out.txt
    )
    

    Reversing 40kb file (10k lines, 1 character in each) took ~1 minute on my machine. Remember it's still only batch. There are many better scripting or programming languages that would be better to perform that operation.

  • Related Question