Skip to content

How to Reverse the Order of Lines in a File in Batch Script

Learn two efficient methods to reverse a file's line order in Windows Batch: a native sort /r tagging technique and a high-performance PowerShell [Array]::Reverse() approach, with best practices for logs, data inversion, and large files.

Sometimes the standard chronological order of a file is exactly the opposite of what you need. For example, in a log file where the newest entries are at the bottom, reversing the file allows you to see the most recent errors at the top. Reversing the order of lines (turning a file "upside down") is a helpful data-processing task that can be automated with Batch.

In this guide, we will demonstrate how to reverse a file by tagging lines with numbers and then performing a reverse sort.

The Strategy: The Reverse Tag

Since the sort command can sort in reverse order, we can:

  1. Read the file and add a zero-padded line number to the start of every line.
  2. Use the sort /r (reverse) command to sort by those numbers in descending order.
  3. Strip the numbers off, leaving the original lines in reverse order.

Method 1: The Native Batch Reverse Sort

Implementation Script

@echo off
setlocal disabledelayedexpansion

set "source=Input.txt"
set "dest=Output.txt"
set "temp=%TEMP%\rev_tagged_%RANDOM%.txt"

:: Verify source file exists
if not exist "%source%" (
    echo [ERROR] Source file "%source%" not found.
    pause
    exit /b 1
)

echo Reversing "%source%"...

:: 1. Add line numbers for sorting
set "count=100000"
(
    for /f "usebackq delims=" %%A in ("%source%") do (
        set /a "count+=1"
        set "line=%%A"
        setlocal enabledelayedexpansion
        echo !count!^|!line!
        endlocal
    )
) > "%temp%"

:: 2. Reverse sort properly using a FOR /F command execution
(
    for /f "usebackq tokens=1* delims=|" %%A in (`sort /r "%temp%"`) do (
        set "line=%%B"
        setlocal enabledelayedexpansion
        echo(!line!
        endlocal
    )
) > "%dest%"

:: 3. Clean up temp file
del "%temp%" 2>nul

echo [SUCCESS] File reversed. Saved to "%dest%".
pause
exit /b 0

For example, if Input.txt contains:

Line 1 - First entry
Line 2 - Second entry
Line 3 - Third entry
Line 4 - Fourth entry
Line 5 - Fifth entry
Line 6 - Sixth entry

The script will produce Output.txt containing:

Line 6 - Sixth entry
Line 5 - Fifth entry
Line 4 - Fourth entry
Line 3 - Third entry
Line 2 - Second entry
Line 1 - First entry

Method 2: The PowerShell Reverse (High Performance)

For large files, the for loop in Method 1 can be slow. PowerShell's [Array]::Reverse() method operates in memory and is significantly faster.

Implementation Script

@echo off
setlocal

set "Source=Input.txt"
set "Dest=Output.txt"

:: Verify source file exists
if not exist "%Source%" (
    echo [ERROR] Source file "%Source%" not found.
    pause
    exit /b 1
)

echo Reversing "%Source%"...

:: Read all lines into an array, reverse in place, and write back
powershell -NoProfile -Command ^
    "$lines = Get-Content -Path '%Source%'; " ^
    "[Array]::Reverse($lines); " ^
    "$lines | Set-Content -Path '%Dest%' -Encoding UTF8"

if %errorlevel% equ 0 (
    echo [SUCCESS] File reversed. Saved to "%Dest%".
) else (
    echo [ERROR] PowerShell reversal failed.
    pause
    exit /b 1
)
pause
exit /b 0

For example, if Input.txt contains:

Line 1 - First entry
Line 2 - Second entry
Line 3 - Third entry
Line 4 - Fourth entry
Line 5 - Fifth entry
Line 6 - Sixth entry

The script will produce Output.txt containing:

Line 6 - Sixth entry
Line 5 - Fifth entry
Line 4 - Fourth entry
Line 3 - Third entry
Line 2 - Second entry
Line 1 - First entry

Practical Uses for Reversing Lines

  1. Log Analysis: Seeing the latest errors at the top of the file without scrolling to the bottom.
  2. Breadcrumb Traces: If a script records its steps sequentially, reversing the list shows the path back to the entry point, providing a stack-trace perspective.
  3. Data Inversion: Transforming a "Last-In, First-Out" (LIFO) list into a "First-In, First-Out" (FIFO) list for task processing.

Best Practices

  1. Verify Source File: Always check that the input file exists before processing. A missing file will produce empty output with no clear error in the Batch method, or a PowerShell exception in Method 2.
  2. Choose a Safe Delimiter: If your data contains the pipe character (|), the delims=| in Method 1 will split your lines incorrectly. Change the delimiter to a character that does not appear in your data, such as § or another rare symbol.
  3. Blank Lines: The Batch method (Method 1) silently drops blank lines due to for /f behavior. The PowerShell method (Method 2) preserves all blank lines. Choose the method that matches your requirements.
  4. Memory vs. Disk: Method 2 loads the entire file into memory. For very large files (multiple gigabytes), this may exhaust system RAM. Method 1 uses temporary files on disk, making it safer for massive datasets on low-memory systems, though it is significantly slower.
  5. Temp File Hygiene: Use the %TEMP% directory for intermediate files and include %RANDOM% in the filename to avoid collisions when multiple instances run simultaneously. Always delete the temp file at the end of the script.
  6. Encoding: Include -Encoding UTF8 in the PowerShell Set-Content command to prevent non-ASCII characters from being corrupted by the default ANSI encoding in PowerShell 5.1.

Conclusion

Reversing the order of lines in a file is a simple but effective technique for changing the perspective of your data. Whether you need to see the latest log entries first or invert a task sequence, the "tag and reverse sort" methodology provides a robust, native solution for any Windows environment. By automating this transformation, you save time and ensure that your data is always presented in the most logical order for your current task.

Navigation