HOWTO · Batch

How to Replace Text From File in Batch Script

Replace text in a file via a batch for loop with delayed expansion, PowerShell's -replace (UTF-8 output), or a sed port; write to a new file and check it first.

On this page

To replace matching text in a file from a Windows command line, write the transformed contents to a separate file and inspect it before using it in place of the source. A batch script can perform simple literal substitutions, PowerShell offers pattern-based replacement, and sed is an option when a Windows port is installed. The examples use a small text file and replace sample with modified.

Replace text with a Windows batch script

This batch example creates its own temporary input, processes each nonblank line, and writes the result to a separate output file. It then displays the output and removes its temporary files. The existing English [echo command]({{relref “/HowTo/Batch/echo command in batch.en.md”}}) reference explains the command used to write each line. findstr can help locate matching lines before or after a change, but it searches; it does not replace text.

@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "work=%TEMP%\batch-replace-%RANDOM%"
md "%work%"
set "inputFile=%work%\input.txt"
set "outputFile=%work%\output.txt"
> "%inputFile%" echo sample text, ready
>> "%inputFile%" echo keep this line
set "search=sample"
set "replace=modified"
(for /f "usebackq delims=" %%L in ("%inputFile%") do (
    set "line=%%L"
    set "line=!line:%search%=%replace%!"
    echo !line!
)) > "%outputFile%"
type "%outputFile%"
del "%inputFile%" "%outputFile%"
rmdir "%work%"
endlocal

for /f "usebackq delims=" %%L in ("%inputFile%") do ... reads lines, delayed expansion applies a literal substitution, and redirecting the loop writes the result to a different file. This simple pattern skips blank lines and delayed expansion can alter lines containing !. Keep search and replacement values simple because batch expansion has special-character rules; use PowerShell when exact line preservation or more complex text matters.

Replace text with PowerShell

PowerShell is available on many Windows systems and is a good fit when the file may contain blank lines or characters that complicate batch expansion. This self-contained example creates the sample input, replaces sample with modified, writes UTF-8 without a byte-order mark, displays the result, and removes its temporary directory.

$work = Join-Path ([IO.Path]::GetTempPath()) ([guid]::NewGuid().ToString())
New-Item -ItemType Directory -Path $work | Out-Null
$inputFile = Join-Path $work 'input.txt'
$outputFile = Join-Path $work 'output.txt'
[IO.File]::WriteAllText($inputFile, "sample text, ready`nkeep this line`n")
$text = [IO.File]::ReadAllText($inputFile)
$result = $text -replace 'sample', 'modified'
$utf8 = New-Object System.Text.UTF8Encoding -ArgumentList $false
[IO.File]::WriteAllText($outputFile, $result, $utf8)
Get-Content -LiteralPath $outputFile
Remove-Item -LiteralPath $work -Recurse -Force
modified text, ready
keep this line

The -replace operator treats its first operand as a regular expression, and matching is case-insensitive by default. For a literal search string containing regex metacharacters, escape it with [regex]::Escape($search); use -creplace when case should matter. The explicit UTF-8 writer avoids relying on version-specific defaults. Review the output file before replacing the original.

Replace text with sed on Windows

sed is not included with every Windows installation. Use it only if a Windows port is installed and available on PATH. Its substitution form is s/search/replacement/g; for this example, run sed "s/sample/modified/g" "input.txt" > "output.txt". The g flag replaces every match on each line, while redirection keeps the source separate from the result.

The search and replacement values are interpreted by sed, so characters such as /, &, and backslashes may need escaping. Check the selected port’s quoting rules when values contain shell-special characters, and inspect the output before using it as the source.

Choose a method and protect the input file

For a short, simple substitution where blank lines and exclamation marks are not significant, the batch loop avoids an extra scripting dependency. PowerShell is a practical default when literal text, regex behavior, or encoding needs control. Choose sed if a Windows port is already available and its substitution syntax fits the data.

Each method should write to a different output path so the input remains intact while the transformation runs. Compare the output with the source and confirm the expected encoding before replacing the original. If the file contains important data, make a backup first; redirecting output to the same path being read can truncate the input before processing finishes.