Last Updated :
28 Nov, 2021
In this article, we are going to Replace a substring with any given string.
Batch Script :
@echo off set str=GFG is the platform for geeks. echo %str% set str=%str:the=best% echo %str% pause
In the above example, we are going to replace ‘the’ by substring ‘best’ using %str:the=best% statement.
Explanation :
- By using ‘ set ‘ we are getting input of any string
set str=input string
- In the next line using ‘ echo %str% ‘ we are printing our string.
- Using ‘ %str:the=best%’ statement , we are replacing substring ‘the’ with ‘best’.
- Then using ‘pause’, to hold the screen until any key is pressed, so that we can read our output.
Output :
‘the’ is replaced by ‘best’
Another Approach :
Batch Script :
@echo off set str=GFG is the platform for geeks. set word=best echo %str% call set str=%%str:the=%word%%% echo %str% pause
Explanation :
- Everything is as same as before, we are trying to replace the word ‘the’ with ‘best’ but we can also do this by calling another variable ‘word’ which is equal to ‘best’.
- By using call there is another layer of variable expansion so we have to use ‘%’ for ‘word’ so that it will use ‘best’ as its value and replace the string.
output by 2nd approach
- SS64
- CMD
- How-to
How-to: Edit/Replace text within a Variable
Use the syntax below to edit and replace the characters assigned to a string
variable, also known as String Substitution.
Syntax %variable:StrToFind=NewStr% %~[param_ext]$variable:Param Key StrToFind : The characters we are looking for (not case sensitive). NewStr : The chars to replace with (if any). variable : The environment variable. param_ext : Any filename Parameter Extension. Param : A command line parameter (e.g. 1).
This Edit/Replace syntax can be used anywhere that you would use the %variable% such as ECHOing the variable to screen or setting one variable = another.
param_ext cannot be %* which typically represents a whole set of parameters, but this is easily worked around by setting a variable=%*
«StrToFind» can begin with an asterisk, in which case it will replace
all characters to the left of «StrToFind».
NewStr can be left blank to delete characters, alternatively include ECHO: in NewStr if you need to generate a CR/newline in the output:
In all cases the string matching is NOT case sensitive, so the string ABC will match abc.
Using both an asterisk and setting NewStr=null will enable you to construct a left$() or right$() function using this syntax.
Examples
The variable _test containing 12345abcabc is
used for all the following examples:
::Replace '12345' with 'Hello ' SET "_test=12345abcABC" SET "_result=%_test:12345=Hello %" ECHO %_result% =Hello abcABC ::Replace the character string 'ab' with 'xy' SET "_test=12345abcABC" SET "_result=%_test:ab=xy%" ECHO %_result% =12345xycxyC ::Delete the character string 'ab' SET "_test=12345abcABC" SET "_result=%_test:ab=%" ECHO %_result% =12345cC ::Delete the character string 'ab' and everything before it SET "_test=12345abcabc" SET "_result=%_test:*ab=%" ECHO %_result% =cabc ::Replace the character string 'ab' and everything before it with 'XY' SET "_test=12345abcabc" SET "_result=%_test:*ab=XY%" ECHO %_result% =XYcabc :: To remove characters from the right hand side of a string is :: a two step process and requires the use of a CALL statement :: e.g. SET _test=The quick brown fox jumps over the lazy dog :: To delete everything after the string 'brown' :: first delete 'brown' and everything before it SET "_endbit=%_test:*brown=%" Echo We dont want: [%_endbit%] ::Now remove this from the original string CALL SET "_result=%%_test:%_endbit%=%%" echo %_result%
The examples above assume the default Expansion of variables, if you are using DelayedExpansion then you can modify variables within a single loop/expression. Use the syntax: !_variable! instead of %_variable%
Rename a set of files (fred001.txt – fred999.txt) with a different prefix, this is similar to but more flexible than a wildcard rename,
via Raymond Chen
Setlocal EnableDelayedExpansion
for %%i in (fred*.txt) do set «_=%%i» & ren «%%i» «!_:fred=wilma!»One other advantage of DelayedExpansion is that it will allow you to replace the % character, it will still have to be escaped as %% but the replace action will then treat it like any other character:
Replace the letter P with a percent symbol:
Setlocal EnableDelayedExpansion
_demo=somePdemoPtextP
_demo=!_demo:P=%%!
Remove spaces from a text string
To delete space characters use the same syntax as above:
SET «_no_spaces=%_some_var: =%«
Boolean Test «does string exist ?»
To test for the existence of a value we can use a temporary variable, delete the string we are looking for (if it exists) and then compare the two variables with EQU
Example: test for the existence of the string «London»
in a variable containing text (that could be in any order) «Aberdeen, London, Edinburgh«Set «_cities=Aberdeen, London, Edinburgh»
:: Remove London if found
Set «_dummy=%_cities:London=%»
IF NOT %_dummy% == %_cities% (ECHO London was found.) ELSE (ECHO London was not found.)
Finding items within the PATH environment variable
The %PATH% variable contains a list of folder names.
If you have a parameter containing a valid ‘folder’ this can be compared with
the PATH variable.This is done using the syntax:
$variable:parameterExamples
%PATH% =
C:\Windows\system32;C:\Windows;C:\utils\jdk\bin
batch parameter %1 =
C:\utils\jdk\binTo get the drive and Path
ECHO %~dp$PATH:1
This will either return «C:\utils\jdk\bin» or a NULL if the item is
not found in the %PATH%If the batch parameter was supplied as %2 then this would be:
ECHO %~dp$PATH:2This syntax can be applied where:
- The parameter is any valid parameter (%1 %2 %G) but it must contain a Full
Path (not a pathname)- The variable is %PATH% or any other variable that contains one or more
Paths or pathnames separated by semicolons ;- If nothing is found by the search, then this will return an empty string
(NULL)Be wary of using the syntax on this page to modify the PATH — the User path can be edited, but the System path remains read-only for most
users.
Advanced Usage of %variable:
You can use the %variable: syntax and provide each of the parameters from other variables, for example if you have
SET «_FullString=The ballad of John and Yoko»
SET «_Search=John»To remove the %_search% string from the%_FullString% you might try:
SET "_result=%_FullString:~%_Search%=%"Unfortunately this will not work because the : syntax expects a value not a
variable.
To work around this use the CALL command, in this case the CALL replaces the variable shown in bold with its value:SET "_FullString=The ballad of John and Yoko" SET "_Search=John" CALL SET "_result=%%_FullString:%_Search%=%%"
:: If nothing was removed then the search string was not found. If /i "%_result%"=="%_FullString%" (Echo String not found) ELSE (Echo String found)
“A phony smile will never replace honest integrity” ~ Bob Martinelli
Related commands
PATH — Display or set a search path for executable files.
How-to: SUBSTRING of a variable :~
How-to: PARAMETERS — Filename Parameter Extensions.
How-to: strlen.cmd — Get string length.
How-to: ToLower.cmd — Lower case a String.
Copyright © 1999-2025 SS64.com
Some rights reserved
Здравствуйте. Сабж. Надо заменить 13ю строку в файле на заранее известную. Пишу так
for /f «skip=12» in (settings.ini) do (echo dparm=BIND=0,lck=’ru’,APP=’GPS’,HST=’%COMPUTERNAME%’)
По задумке должно пропустить 12 строк с начала файла и заменить на то, что указано в скобках. По факту — ноль реакции. Возможно, надо еще прервать цикл, т.к. замена производится один раз, но не уверен, это предположение, раньше с смд дел не имел.
-
Вопрос задан
-
7711 просмотров
В общем, полазил еще по форумам и сделал. Изначально задача была заменить в файле кусок именем компьютера, на котором запущен файл. Но я намудрил, решил заменить целую строчку, поэтому долго возился. Все оказалось прозаичнее. В примере ниже pc-name — это кусок, подлежащий замене на имя компа, получаемое через %computername%.
@echo off
setlocal enabledelayedexpansion
Set infile=settings.ini
Set find=pc-name
Set replace=%COMPUTERNAME%
@echo off
setlocal enabledelayedexpansion
set COUNT=0
for /F «tokens=* delims=, eol=#» %%n in (!infile!) do (
set LINE=%%n
set TMPR=!LINE:%find%=%replace%!
Echo !TMPR!>>TMP.TXT
)
move TMP.TXT %infile%
Пригласить эксперта
Контент в 12-й строке известен?
как вариант
Можно PowerShell
$FilePath = C:\path_to_settings.ini
(Get-Content $FilePath) -replace 'parametr =.*','parametr = "YOUR TEXT"' | Out-File $FilePath
На PowerShell делается просто
Запустить PoSH из скрипта в командной строке : (содержимое bat файла)
powershell "$f=(Get-Content вашфайлик);$f[номерстроки]='новыйконтент';$f | set-content вашфайлик"
И никто не заставляет писать монструозные конструкции, правда?
Set find=pc-name возможно заменить на Set find=pc-name*, т.е. применив маску к токену?
Войдите, чтобы написать ответ
-
Показать ещё
Загружается…
Минуточку внимания
How to Find and Replace Text in a File using Windows Command-Line 🖥️
So, you’re a command-line enthusiast and need to find and replace text in a file quickly? Look no further! In this guide, we’ll show you the simplest way to accomplish this task using the Windows command-line environment.
The Problem: Finding and Replacing Text 🎯
Let’s say you have a batch file script, and you want to change every occurrence of a specific text in a file. For example, you want to replace all instances of «FOO» with «BAR». How can you accomplish this without spending hours manually editing the file?
The Solution: The findstr
and copy
Commands 💡
Thankfully, Windows provides two powerful commands — findstr
and copy
— that can help us find and replace text efficiently.
-
Open the Windows Command Prompt by pressing
Win
+R
, typingcmd
, and hittingEnter
. -
Navigate to the directory where your file is located using the
cd
(change directory) command. For example, if your file is in the «Documents» folder, typecd Documents
and hitEnter
. -
Now, let’s use the
findstr
command to identify the lines containing the text we want to replace. Execute the following command:findstr /C:"FOO" your_file.txt > temporary.txt
This command searches for the string «FOO» in the file
your_file.txt
and redirects the output to a temporary file calledtemporary.txt
. -
Open the temporary file (
temporary.txt
) in your favorite text editor and perform a search and replace operation there. Replace all occurrences of «FOO» with «BAR», for example. -
Once you’ve made the necessary changes, save and close the temporary file.
-
Finally, use the
copy
command to replace the original file with the modified temporary file. Execute the following command:copy /Y temporary.txt your_file.txt
The
/Y
option ensures that the command won’t prompt for confirmation each time.
Congratulations! 🎉 You’ve successfully found and replaced text in a file using the Windows command-line. This method allows you to change text swiftly and efficiently.
An Easier Alternative: PowerShell 📑
If you’re comfortable using PowerShell, you can achieve the same results with fewer steps. Here’s an alternative method:
-
Open PowerShell by pressing
Win
+R
, typingpowershell
, and hittingEnter
. -
Navigate to the directory containing your file using the
cd
command, just like we did in the previous method. -
Execute the following PowerShell command to replace the text:
(Get-Content your_file.txt).Replace('FOO', 'BAR') | Set-Content your_file.txt
This command reads the content of the file, replaces «FOO» with «BAR», and writes the modified contents back to the same file.
That’s it! Using PowerShell, you can achieve the same result in a single command.
Take Command of Your Text Files with Ease! 🚀
Now you know how to find and replace text in a file using the Windows command-line environment. Whether you prefer the simplicity of the findstr
and copy
commands or the power of PowerShell, you’ll be able to make changes to your files swiftly.
So, the next time you encounter the need to replace text in a file, put these techniques to use and save yourself valuable time. Remember, command-line mastery is just a few commands away!
Let us know in the comments which method you prefer or if you have any other command-line tricks up your sleeve. Stay in command! 💪
-
How to Replace Text From File in Batch Script Using
findstr
andecho
-
How to Replace Text From File in Batch Script Using Windows PowerShell
-
How to Replace Text From File in Batch Script Using
sed
-
Conclusion
In Batch scripting and automation, the ability to efficiently manipulate text within files is a crucial skill. Whether you’re a seasoned system administrator, a curious enthusiast, or a developer seeking to streamline your workflow, text replacement in Batch files is a valuable asset.
This article delves into three methods to handle string replacement tasks on a Windows system: the findstr
and echo
commands, Windows PowerShell, and the sed
tool.
Text replacement is a common requirement in various scenarios, ranging from modifying configuration files to updating code snippets. Each method discussed here brings its unique strengths to the table, catering to different preferences and situations.
How to Replace Text From File in Batch Script Using findstr
and echo
The findstr
command is a powerful tool for searching for text patterns in files. It supports regular expressions and various search options.
In the following example script, we use findstr
to locate lines containing the text substring we want to replace within the specified file.
On the other hand, the [echo
command]({{relref “/HowTo/Batch/echo command in batch.en.md”}}) is used for displaying messages or, in our case, for outputting modified content to the original file. We leverage the for /f
loop to read each line from the temporary file, replace the desired text, and then echo
the modified line back to the original file.
This approach is particularly useful when you want to perform replacements on a line-by-line basis in a given file.
Sample File: textFile.txt
Let’s consider a sample text file named textFile.txt
with the following content:
Replace String From File Using findstr
and echo
Code Example 1
Now, let’s take a look at the Batch code that replaces the specified text:
@echo off
setlocal enabledelayedexpansion
rem delayed variable expansion, allowing variables to be expanded at execution time.
set "search=sample"
set "replace=modified"
set "inputFile=textFile.txt"
set "outputFile=output.txt"
(for /f "tokens=*" %%a in ('type "%inputFile%" ^| findstr /n "^"') do (
set "line=%%a"
set "line=!line:*:=!"
if defined line (
set "line=!line:%search%=%replace%!"
echo(!line!
) else echo.
)) > "%outputFile%"
endlocal
rem end local scope to clean up environment variable.
Here, we begin by turning off the default echoing of commands with @echo off
, ensuring that only the desired output is displayed. The setlocal enabledelayedexpansion
command is used to enable delayed variable expansion, a crucial feature for working with variables within loops.
Next, we set up variables: search
holds the text we want to find (sample
), replace
contains the replacement text (modified
), inputFile
points to path to the source file (textFile.txt
), and outputFile
designates the path to the file where the modified content will be stored (output.txt
).
The core of the script lies in the for
loop, which iterates through each line of the given file. The type "%inputFile%" ^| findstr /n "^"
command extracts each line, and the for /f "tokens=*" %%a
parses the lines.
Within the loop, the line number is stripped off with set "line=!line:*:=!"
.
Conditional checks follow to ensure that the line is not empty. If a line contains text, the set "line=!line:%search%=%replace%!"
command performs the actual text replacement using the values in the search
and replace
variables.
Finally, the modified line is echoed to the console with echo(!line!
.
The entire loop, the function which handles the replacement and echoing, is encapsulated within parentheses, and the output is redirected to the specified output file (%outputFile%
) using the >
operator.
The script concludes with the endlocal
command, ensuring that the changes in environment variable states are confined to the script’s scope.
Code Output:
Replace String From File Using findstr
and echo
Code Example 2
Let’s enhance the existing script to demonstrate how to replace two or more consecutive words in a text file. Here, we’ll replace the words sample text
with modified content
.
@echo off
setlocal enabledelayedexpansion
rem delayed variable expansion, allowing variables to be expanded at execution time.
set "search=sample text"
set "replace=modified content"
set "inputFile=textFile.txt"
set "outputFile=output.txt"
(for /f "tokens=*" %%a in ('type "%inputFile%" ^| findstr /n "^"') do (
set "line=%%a"
set "line=!line:*:=!"
if defined line (
set "line=!line:%search%=%replace%!"
echo(!line!
) else echo.
)) > "%outputFile%"
endlocal
rem end local scope to clean up environment variable.
In this modified script, the search
variable now contains the phrase sample text
, and the replace
variable holds the replacement modified content
. The script will identify and replace occurrences of sample text
with modified content
throughout the text file.
Code Output:
This demonstrates the flexibility of the script in handling replacements of multiple consecutive words. You can customize the search
and replace
variables to match the specific words or phrases you want to replace in your text file.
How to Replace Text From File in Batch Script Using Windows PowerShell
Another approach we can use to perform text replacement in Batch files is PowerShell—a versatile scripting language that seamlessly integrates with Windows environments. Specifically, we can use PowerShell’s -replace
operator.
The -replace
operator in PowerShell is designed for pattern-based string manipulation. It allows you to specify a search pattern and its replacement within a string.
In the context of Batch Scripting, this operator becomes a valuable asset to enable string substitution feature.
Replace String From File Using Windows PowerShell Code Example
Let’s use the same sample file named textFile.txt
:
@echo off
set "search=sample"
set "replace=modified"
set "inputFile=textFile.txt"
set "outputFile=output.txt"
powershell -Command "(gc %inputFile%) -replace '%search%', '%replace%' | Out-File -encoding ASCII %outputFile%"
In this example, we begin with the directive @echo off
to suppress the echoing of commands. Following that, we set up variables: search
holds the text we want to find (sample
), replace
contains the replacement text (modified
), inputFile
points to the source file (textFile.txt
), and outputFile
designates the file where the modified content or text string will be stored (output.txt
).
The core of the script lies in the powershell -Command
line. Here, we leverage PowerShell’s -replace
operator to perform and execute the text replacement.
The (gc %inputFile%)
part reads the content of the input file, and -replace '%search%', '%replace%'
specifies the search and replacement patterns. The | Out-File -encoding ASCII %outputFile%
section saves the updated content to the specified output file using the PowerShell Out-File
cmdlet.
Code Output:
How to Replace Text From File in Batch Script Using sed
The integration of powerful text processing tools adds another layer of versatility to your toolkit. One such tool is sed
, a stream editor that originated in Unix environments, but thanks to ports like GnuWin32, sed
is available for Windows, providing a command-line utility that can be seamlessly integrated into the command prompt.
sed
stands for stream editor, designed for parsing and transforming text streams. In our context, the Windows port of sed
allows us to perform sophisticated text replacements directly within a Batch file.
This provides a flexible and powerful alternative for scenarios where other native solutions might fall short.
Replace String From File Using sed
Code Example
Let’s continue using our sample file named textFile.txt
:
@echo off
set "search=sample"
set "replace=modified"
set "inputFile=textFile.txt"
set "outputFile=output.txt"
sed "s/%search%/%replace%/g" "%inputFile%" > "%outputFile%"
In this example, we also begin with @echo off
to suppress the echoing of commands. Subsequently, we set up the same variables: search
, replace
, inputFile
, and outputFile
.
The core of the script lies in the sed "s/%search%/%replace%/g" "%inputFile%" > "%outputFile%"
command line call. Here, the sed
command reads the content of the %inputFile%
, searches for occurrences of characters in the specified search
text, and replaces them with the replace
text.
The s/%search%/%replace%/g
syntax defines the search strings and replacement patterns, and the > "%outputFile%"
section directs the modified content to write the specified output file.
Code Output:
This test script effectively replaced the specified text string in the test file with another string, using the Windows port of sed
, demonstrating the versatility of Batch Scripting in handling advanced text processing tasks.
Conclusion
Throughout this article, we’ve delved into three distinct methods, each offering its unique strengths and approaches.
The use of findstr
and echo
commands provides a native and straightforward solution. Its simplicity and reliance on familiar commands make it an accessible choice for those looking to perform text replacements efficiently within a Windows Batch file.
Windows PowerShell, with its -replace
operator, introduces a powerful and dynamic way to manipulate text. Its seamless integration into Batch Scripting allows for intricate replacements and pattern-based transformations, providing a versatile tool for those comfortable with PowerShell’s capabilities.
For users seeking advanced text processing capabilities, the incorporation of sed
proves invaluable. As a Windows port of a Unix-originated stream editor, sed
brings a wealth of functionality for complex text manipulations, expanding the toolkit for seasoned scripters and administrators.
Each method caters to specific needs and preferences, offering flexibility in handling diverse text replacement tasks.
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe