How to Prepend Text to Every Line in a File in Batch Script
Prepending text (adding a prefix) to every line in a file is a frequent requirement in data processing. You might need to add a timestamp to every log entry, prepend a drive letter to a list of paths, or add a specific code (like DELETE ) to every line of a batch-processing manifest. While modern text editors have a "Column Mode," automating this via Batch allows you to handle thousands of files instantly.
In this guide, we will demonstrate how to prepend text using a for /f loop.
Method 1: The Standard Loop (FOR /F)
This method reads each line and outputs it back with your desired prefix attached to the front.
@echo off
setlocal disabledelayedexpansion
set "Source=FileList.txt"
set "Dest=Processed_FileList.txt"
set "Prefix=C:\Data\"
:: Verify source file exists
if not exist "%Source%" (
echo [ERROR] Source file "%Source%" not found.
pause
exit /b 1
)
echo Prepending "%Prefix%" to every line in "%Source%"...
(
for /f "usebackq delims=" %%A in ("%Source%") do (
set "line=%%A"
setlocal enabledelayedexpansion
echo(!Prefix!!line!
endlocal
)
) > "%Dest%"
echo [SUCCESS] Prefixed file saved to "%Dest%".
pause
exit /b 0
For example, if you have a file named FileList.txt with the following content:
file1.txt
file2.txt
file3.txt
And you run the script with set "Prefix=C:\Data\", the output file Processed_FileList.txt will contain:
C:\Data\file1.txt
C:\Data\file2.txt
C:\Data\file3.txt
The for /f loop skips blank lines by design and also skips lines beginning with ; (the default eol character). Blank lines in the original file will be removed from the output, and lines starting with ; will be silently dropped. For files where every line must be preserved, use the PowerShell method (Method 2).
The script uses the delayed expansion toggle pattern: each line is set with delayed expansion disabled (set "line=%%A") to preserve literal ! characters in the file content. The prefix and line are then combined with delayed expansion enabled (echo(!Prefix!!line!) to safely handle &, |, >, <, and other special characters in both the prefix and the line content. The echo( syntax also prevents ECHO is off. messages for empty values.
Method 2: The PowerShell Bridge (Recommended for Complex Data)
If your file contains special characters or blank lines that must be preserved, PowerShell provides a safer and faster approach.
@echo off
setlocal
set "Source=FileList.txt"
set "Dest=Processed_FileList.txt"
set "Prefix=[IMPORT] "
:: Verify source file exists
if not exist "%Source%" (
echo [ERROR] Source file "%Source%" not found.
pause
exit /b 1
)
echo Prepending "%Prefix%" to every line in "%Source%"...
:: ForEach-Object concatenates the prefix with each line
:: Blank lines are preserved with the prefix prepended
powershell -NoProfile -Command ^
"$prefix = '%Prefix%'; " ^
"Get-Content -Path '%Source%' | " ^
"ForEach-Object { $prefix + $_ } | " ^
"Set-Content -Path '%Dest%' -Encoding UTF8"
if %errorlevel% equ 0 (
echo [SUCCESS] Prefixed file saved to "%Dest%".
) else (
echo [ERROR] Prepend operation failed.
pause
exit /b 1
)
pause
exit /b 0
The PowerShell method preserves blank lines and handles all special characters without escaping. Blank lines in the source will appear as lines containing only the prefix text in the output, which is the correct behavior for most prepend operations. If you want blank lines to remain truly blank (no prefix), add a condition: ForEach-Object { if ($_.Length -gt 0) { $prefix + $_ } else { $_ } }.
Why Prepend Text?
- Command Preparation: If you have a list of file names and want to turn them into a list of deletion commands, you can prepend
del /q /f. - Breadcrumbs: Adding the name of the source server to the beginning of every line in a combined log file so you know which server generated which error.
- Data Categorization: Prepending a category label (e.g.,
USER:,ADMIN:,SYSTEM:) to raw export data to make it easier to filter later withfindstr.
Best Practices
- Verify Source File: Always check that the input file exists before processing. A missing file will cause the
for /floop to silently produce empty output, and the redirection will create an empty destination file. - Blank Lines: The Batch
for /fmethod drops blank lines. If your file uses blank lines as section separators, those separators will disappear from the output. Use Method 2 to preserve them. - Special Characters in Prefix: If the prefix itself contains special Batch characters (
&,|,<,>,^), the delayed expansion pattern in Method 1 handles them safely through!Prefix!. Never useecho %Prefix%%%Awith percent expansion, as special characters in either the prefix or the line content will be interpreted as command operators. - Special Characters in Content: Lines containing
&,|,>,<, or!require the delayed expansion toggle pattern. The originalecho %Prefix%%%Aapproach would break on any of these characters. - Performance: For files larger than 10 MB, the Batch loop can be noticeably slow. The PowerShell method is optimized for streaming large text files efficiently.
- Encoding: Include
-Encoding UTF8in the PowerShellSet-Contentcommand to prevent non-ASCII characters from being corrupted by the default ANSI encoding in PowerShell 5.1. - Path Prefixes: When prepending file system paths (like
C:\Data\), ensure the prefix ends with the correct path separator. A missing trailing backslash would produceC:\Datafilename.txtinstead ofC:\Data\filename.txt.
Conclusion
Prepending text is a small but essential transformation that prepares your data for the next stage of its lifecycle. Whether you are building a batch script manifest or tagging logs for an audit, the ability to programmatically add prefixes to every line ensures that your workflows remain consistent and your data remains clearly identified. By mastering the for /f loop and PowerShell bridges, you can manage bulk text modifications with confidence.