Skip to main content

How to Add Line Numbers to a Text File in Batch Script

When reviewing long log files or comparing versions of a configuration script, having Line Numbers (e.g., 1: data, 2: data) makes it much easier to discuss specific parts of the file with a teammate or to pinpoint an error location. While you can use a text editor to see line numbers, adding them directly to the file via a Batch script is essential for generating automated reports or printable audits.

In this guide, we will demonstrate how to add line numbers using the findstr and find commands.

Method 1: The Fast Way (FINDSTR)

The findstr command has a built-in switch (/n) that prefixes every matching line with its line number and a colon. By searching for the regex pattern . (any single character), we can number every non-blank line in the file.

Implementation Script

@echo off
setlocal

set "Source=LogFile.txt"
set "Output=NumberedLog.txt"

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

echo Adding line numbers to "%Source%"...

:: /n prefixes each matching line with its line number and a colon
:: /r enables regular expressions
:: "." matches any single character, so only non-blank lines are output
:: Blank lines are skipped entirely (use Method 2 to preserve them)
findstr /n /r "." "%Source%" > "%Output%"

:: findstr returns 0 if matches were found, 1 if no lines matched
:: (empty file or all blank lines), and 2 or higher on error.
:: Return code 1 is a valid result (empty output), not an error.
if %errorlevel% gtr 1 (
echo [ERROR] Failed to process file.
pause
exit /b 1
)

echo [SUCCESS] Numbered file saved to "%Output%".
pause
exit /b 0
warning

The findstr /n /r "." approach skips blank lines because the . pattern requires at least one character to match. Any blank lines in the source file will be absent from the output, and the remaining line numbers will still reflect the original positions, leaving visible gaps in the numbering sequence. If you need blank lines preserved, use Method 2 instead.

Method 2: The "Blank Line Aware" Method (FIND)

The findstr method above skips completely blank lines. If your file contains blank lines that you want to preserve in the numbering, use the find command instead.

@echo off
setlocal

set "Source=document.txt"
set "Output=numbered_document.txt"

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

echo Adding line numbers to "%Source%"...

:: /n adds line numbers in [N] format
:: /v "" matches all lines including blank lines
:: Reading from stdin with < avoids the filename header that
:: find prints when given a file argument directly
find /n /v "" < "%Source%" > "%Output%"

echo [SUCCESS] Numbered file saved to "%Output%".
pause
exit /b 0
tip

When find receives a filename as an argument (e.g., find /n /v "" "file.txt"), it prepends a ---------- file.txt header line to the output. Reading from standard input with < "file.txt" suppresses this header, producing clean numbered output starting directly at [1].

info

The output format of find /n uses square brackets: [1]First line, [2]Second line, etc. This differs from the findstr /n format which uses a colon: 1:First line, 2:Second line. Choose the method that produces the format your downstream processing expects.

Method 3: Custom Formatting (The FOR Loop)

If you need a format different from the [1] or 1: styles provided by the built-in commands, such as Line 001 -- content, you can use a for /f loop with a counter.

Implementation Script

@echo off
setlocal disabledelayedexpansion

set "Source=config.ini"
set "Output=custom_numbered.txt"

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

set "count=0"

(
for /f "usebackq delims=" %%A in ("%Source%") do (
set /a "count+=1"
set "line=%%A"
setlocal enabledelayedexpansion
:: Pad numbers with leading zeros (3 digits supports up to 999 lines)
set "num=000!count!"
echo Line !num:~-3! -- !line!
endlocal
)
) > "%Output%"

echo [SUCCESS] Line numbers added. Result saved to "%Output%".
pause
exit /b 0
warning

The for /f loop skips blank lines by design and also skips lines beginning with ; (the default eol character). This means the output will be missing those lines, and the custom line numbers will not correspond to the original line positions. For files where blank lines or ;-prefixed lines must be preserved, use Method 2 instead.

tip

The script uses the delayed expansion toggle pattern: the line variable is set with delayed expansion disabled (set "line=%%A") to preserve literal ! characters in the file content. It is then read with delayed expansion enabled (echo Line !num:~-3! -- !line!) to safely handle &, |, >, <, and other special characters during output.

Why Add Line Numbers via Script?

  1. Automated Error Reporting: If your script finds a specific keyword (like "WARNING") in a file, it can report: "Warning found on line 45."
  2. Audit Trails: When archiving data, having a column of numbers ensures that no lines were lost or accidentally deleted during the transfer.
  3. Code Presentation: If you are building a tool that displays code snippets in the console, line numbers provide a professional "IDE-like" appearance.

Best Practices

  1. Verify Source File: Always check that the input file exists before processing. Both findstr and find may produce empty output files with no meaningful error when the source is missing.
  2. Format Consistency: Decide if you want a colon (1:), a bracket ([1]), or a custom prefix as your separator and stick to it throughout the project.
  3. Choose the Right Method: Use findstr (Method 1) for speed when blank lines are irrelevant. Use find (Method 2) when blank lines must be preserved with accurate numbering. Use the for /f loop (Method 3) only when you need custom formatting and can accept its limitations with blank lines and semicolons.
  4. Handling Large Files: The findstr and find methods are fast, processing thousands of lines in milliseconds. The for /f loop method is significantly slower and should be reserved for smaller files where custom formatting is required.
  5. Original Integrity: Never overwrite your source file. Always output to a separate filename so you keep the raw data intact for verification.
  6. Padding Width: When using zero-padded line numbers in Method 3, choose a padding width that accommodates the expected file size. Three digits (000) supports up to 999 lines. For larger files, increase the padding (e.g., 00000!count! with !num:~-5! for up to 99,999 lines).

Conclusion

Adding line numbers to a text file is a simple but high-impact way to improve the readability and utility of your data.

Whether you need a quick one-liner for an audit report or a custom-formatted list for a user interface, Batch provides the tools to organize your text streams with precision.

This clarity is essential for effective troubleshooting and system communication.