How can you find and replace text in a file using the Windows command line environment?
This section contains many methods on how to perform a replacement from the command line.
My favorite is the free Xchang32 tool from the Clay Utilities for Win32 collection , because it can even be used for binary files.
The following command is used for this task:
Xchang32.exe "Test.txt" "~ST" "^x0D^x0A~ST"
^x0D is the hexadecimal notation for carriage return.
^x0A is the hexadecimal notation for the string.
Why use the Xchang32.exe tool to search and replace files instead of the standard Windows commands?
This is similar to the question why using a hammer to bring a nail into the board, and not, for example, diagonal pliers. You can drive a nail into a board with diagonal pliers, as I already did in the past. But it is much easier to use a hammer, which is designed to bring nails to the board.
Therefore, using standard Windows commands to replace a line in a file is possible, although it is not intended for. But itβs much easier to use a free tool, for example Xchang32.exe , which is designed specifically for this task.
The following batch file can be used for the entire task with GARBAGE being an unknown string.
@echo off Xchang32.exe "Test.txt" "~ST" "^x0D^x0A~ST" >nul if errorlevel 1 goto :EOF setlocal EnableDelayedExpansion Xchang32.exe "Test.txt" "~GE" "^x0D^x0A~GE" >nul del "%TEMP%\Test.tmp" 2>nul for /F "usebackq skip=1 delims=" %%L in ("Test.txt") do ( set "Line=%%L" if "!Line:~1,2!" == "ST" echo %%L>>"%TEMP%\test.tmp" ) move /Y "%TEMP%\Test.tmp" "Test.txt" endlocal
source share