How to Display the First N Lines of a File in Batch Script
When working with large text files, it's often inefficient to open the entire file just to see its beginning. You might need to check the header row of a CSV, inspect the first few entries of a massive log file, or simply get a preview of a document's content. While Windows Batch doesn't have a direct equivalent to the Linux head command, you can easily replicate this functionality using a simple FOR loop with a counter.
This guide will teach you the standard batch script method for displaying the first N lines of a file, introduce the much simpler and more modern approach using PowerShell, and show you how to handle edge cases like empty lines and small files.
1. The Core Method: FOR /F Loop with a Counter
This is the traditional, "pure-batch" way to solve the problem. It is flexible and works in any environment, but is more verbose than modern alternatives.
The logic is the following:
- Enable
DelayedExpansionto allow a counter variable to be updated and read inside a loop. - Use a
FOR /Floop to read the file line by line. - Inside the loop, increment a counter.
- Display the current line.
- Check if the counter has reached the desired number of lines (
N). If it has, useGOTOto exit the loop immediately, preventing the script from reading the rest of the large file.
This is the script:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "FILENAME=large_log_file.log"
SET "LINES_TO_SHOW=10"
SET "count=0"
FOR /F "delims=" %%L IN (%FILENAME%) DO (
SET /A "count+=1"
ECHO %%L
IF !count! EQU %LINES_TO_SHOW% GOTO :Done
)
:Done
ECHO.
ECHO --- End of preview ---
The Modern Method: Using PowerShell for Simplicity
For any modern Windows system, calling a short PowerShell command is a far simpler and more robust solution. PowerShell's Get-Content cmdlet has a built-in parameter for this exact task.
The Syntax
powershell -Command "Get-Content 'filename.txt' -TotalCount N"
Get-Content: The PowerShell cmdlet for reading files.-TotalCount N: This parameter tells it to stop reading after it has retrievedNlines.
This single line is a complete replacement for the entire batch loop.
Basic Example: Displaying the First 5 Lines
Let's display the start of a sample CSV file using both methods.
For example, consider this sales_data.csv file:
Date,Region,Product,Amount
2023-10-25,North,Widget,150
2023-10-25,South,Gadget,220
2023-10-26,North,Widget,135
2023-10-26,West,Sprocket,500
2023-10-26,South,Gadget,210
...
Method 1: Batch FOR /F Loop
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "count=0"
FOR /F "delims=" %%L IN (sales_data.csv) DO (
SET /A count+=1
ECHO %%L
IF !count! EQU 5 GOTO :Done
)
:Done
Output
Date,Region,Product,Amount
2023-10-25,North,Widget,150
2023-10-25,South,Gadget,220
2023-10-26,North,Widget,135
Method 2: PowerShell One-Liner
@ECHO OFF
powershell -Command "Get-Content 'sales_data.csv' -TotalCount 5"
Output (same as method 1)
Date,Region,Product,Amount
2023-10-25,North,Widget,150
2023-10-25,South,Gadget,220
2023-10-26,North,Widget,135
Common Pitfalls and How to Solve Them
Problem: Empty Lines are Skipped
The standard FOR /F loop will skip over any empty lines in a file, which can give you an inaccurate preview.
For example, using the FOR /F loop on our sales_data.csv would actually show 6 lines of content because it skips the blank line (line 4) and keeps reading until it has found 5 non-empty lines.
Solution: Use FINDSTR (Batch) or PowerShell
To make the batch method reliable, you must pipe the file through FINDSTR /N "^" to number every line, preventing any from being skipped.
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "count=0"
FOR /F "tokens=1,* delims=:" %%A IN ('FINDSTR /N "^" sales_data.csv') DO (
SET /A count+=1
ECHO %%B
IF !count! EQU 5 GOTO :Done
)
:Done
This is much more complex. By contrast, the PowerShell Get-Content command handles empty lines correctly by default, which is another major advantage.
Problem: The File Has Fewer Lines Than Requested
What happens if you ask for the first 100 lines of a file that only has 50?
- Batch
FOR /Floop: It will simply read and display all 50 lines and then the script will end. No error occurs. - PowerShell
Get-Content: It behaves the same way, displaying all 50 lines without any error.
This is generally the desired behavior, so it's not a problem that needs fixing.
Problem: Capturing the Output to a New File
Instead of just displaying the lines, you may want to create a new, smaller file with the preview.
Solution: Use Redirection
Both methods can easily have their output redirected.
Batch FOR /F Loop:
Wrap the entire loop in parentheses and redirect the output.
(FOR /F ... DO (
...
)) > preview.txt
PowerShell:
Simply pipe the PowerShell output to Set-Content.
powershell -Command "Get-Content 'sales_data.csv' -TotalCount 5 | Set-Content 'preview.csv'"
The PowerShell method is again cleaner and more direct.
Practical Example: Creating a CSV Preview File
This script uses the robust PowerShell method to create a sample.csv file containing the header and the first 10 rows of data from a large master file.
@ECHO OFF
SETLOCAL
SET "MASTER_FILE=C:\BigData\all_transactions.csv"
SET "SAMPLE_FILE=C:\Reports\transaction_sample.csv"
SET "LINES_TO_EXTRACT=11"
ECHO --- CSV Preview Generator ---
ECHO.
IF NOT EXIST "%MASTER_FILE%" (
ECHO [ERROR] Master file not found: %MASTER_FILE%
GOTO :End
)
ECHO Creating a %LINES_TO_EXTRACT%-line sample: %SAMPLE_FILE%
powershell -Command "Get-Content '%MASTER_FILE%' -TotalCount %LINES_TO_EXTRACT% | Set-Content '%SAMPLE_FILE%'"
ECHO.
ECHO [SUCCESS] Sample file created.
:End
ENDLOCAL
Conclusion
Previewing the beginning of a file is a simple task with two good solutions in modern Windows.
- The
FOR /Floop with a counter is the traditional, pure-batch method. It is flexible but requires more code and careful handling of empty lines. - The PowerShell
Get-Content -TotalCount Ncommand is the modern, recommended approach. It is more concise, more powerful, and correctly handles edge cases like empty lines with no extra effort.
For most scripting needs, the PowerShell one-liner is the superior choice for its simplicity and reliability.