Note — Be sure to see the update at the end of this answer for a link to the superior JREPL.BAT that supersedes REPL.BAT
JREPL.BAT 7.0 and above natively supports unicode (UTF-16LE) via the /UTF
option, as well as any other character set, including UTF-8, via ADO!!!!
I have written a small hybrid JScript/batch utility called REPL.BAT that is very convenient for modifying ASCII (or extended ASCII) files via the command line or a batch file. The purely native script does not require installation of any 3rd party executeable, and it works on any modern Windows version from XP onward. It is also very fast, especially when compared to pure batch solutions.
REPL.BAT simply reads stdin, performs a JScript regex search and replace, and writes the result to stdout.
Here is a trivial example of how to replace foo with bar in test.txt, assuming REPL.BAT is in your current folder, or better yet, somewhere within your PATH:
type test.txt|repl "foo" "bar" >test.txt.new
move /y test.txt.new test.txt
The JScript regex capabilities make it very powerful, especially the ability of the replacement text to reference captured substrings from the search text.
I’ve included a number of options in the utility that make it quite powerful. For example, combining the M
and X
options enable modification of binary files! The M
Multi-line option allows searches across multiple lines. The X
eXtended substitution pattern option provides escape sequences that enable inclusion of any binary value in the replacement text.
The entire utility could have been written as pure JScript, but the hybrid batch file eliminates the need to explicitly specify CSCRIPT every time you want to use the utility.
Here is the REPL.BAT script. Full documentation is embedded within the script.
@if (@X)==(@Y) @end /* Harmless hybrid line that begins a JScript comment
::************ Documentation ***********
::REPL.BAT version 6.2
:::
:::REPL Search Replace [Options [SourceVar]]
:::REPL /?[REGEX|REPLACE]
:::REPL /V
:::
::: Performs a global regular expression search and replace operation on
::: each line of input from stdin and prints the result to stdout.
:::
::: Each parameter may be optionally enclosed by double quotes. The double
::: quotes are not considered part of the argument. The quotes are required
::: if the parameter contains a batch token delimiter like space, tab, comma,
::: semicolon. The quotes should also be used if the argument contains a
::: batch special character like &, |, etc. so that the special character
::: does not need to be escaped with ^.
:::
::: If called with a single argument of /?, then prints help documentation
::: to stdout. If a single argument of /?REGEX, then opens up Microsoft's
::: JScript regular expression documentation within your browser. If a single
::: argument of /?REPLACE, then opens up Microsoft's JScript REPLACE
::: documentation within your browser.
:::
::: If called with a single argument of /V, case insensitive, then prints
::: the version of REPL.BAT.
:::
::: Search - By default, this is a case sensitive JScript (ECMA) regular
::: expression expressed as a string.
:::
::: JScript regex syntax documentation is available at
::: http://msdn.microsoft.com/en-us/library/ae5bf541(v=vs.80).aspx
:::
::: Replace - By default, this is the string to be used as a replacement for
::: each found search expression. Full support is provided for
::: substituion patterns available to the JScript replace method.
:::
::: For example, $& represents the portion of the source that matched
::: the entire search pattern, $1 represents the first captured
::: submatch, $2 the second captured submatch, etc. A $ literal
::: can be escaped as $$.
:::
::: An empty replacement string must be represented as "".
:::
::: Replace substitution pattern syntax is fully documented at
::: http://msdn.microsoft.com/en-US/library/efy6s3e6(v=vs.80).aspx
:::
::: Options - An optional string of characters used to alter the behavior
::: of REPL. The option characters are case insensitive, and may
::: appear in any order.
:::
::: A - Only print altered lines. Unaltered lines are discarded.
::: If the S options is present, then prints the result only if
::: there was a change anywhere in the string. The A option is
::: incompatible with the M option unless the S option is present.
:::
::: B - The Search must match the beginning of a line.
::: Mostly used with literal searches.
:::
::: E - The Search must match the end of a line.
::: Mostly used with literal searches.
:::
::: I - Makes the search case-insensitive.
:::
::: J - The Replace argument represents a JScript expression.
::: The expression may access an array like arguments object
::: named $. However, $ is not a true array object.
:::
::: The $.length property contains the total number of arguments
::: available. The $.length value is equal to n+3, where n is the
::: number of capturing left parentheses within the Search string.
:::
::: $[0] is the substring that matched the Search,
::: $[1] through $[n] are the captured submatch strings,
::: $[n+1] is the offset where the match occurred, and
::: $[n+2] is the original source string.
:::
::: Arguments $[0] through $[10] may be abbreviated as
::: $1 through $10. Argument $[11] and above must use the square
::: bracket notation.
:::
::: L - The Search is treated as a string literal instead of a
::: regular expression. Also, all $ found in the Replace string
::: are treated as $ literals.
:::
::: M - Multi-line mode. The entire contents of stdin is read and
::: processed in one pass instead of line by line, thus enabling
::: search for n. This also enables preservation of the original
::: line terminators. If the M option is not present, then every
::: printed line is terminated with carriage return and line feed.
::: The M option is incompatible with the A option unless the S
::: option is also present.
:::
::: Note: If working with binary data containing NULL bytes,
::: then the M option must be used.
:::
::: S - The source is read from an environment variable instead of
::: from stdin. The name of the source environment variable is
::: specified in the next argument after the option string. Without
::: the M option, ^ anchors the beginning of the string, and $ the
::: end of the string. With the M option, ^ anchors the beginning
::: of a line, and $ the end of a line.
:::
::: V - Search and Replace represent the name of environment
::: variables that contain the respective values. An undefined
::: variable is treated as an empty string.
:::
::: X - Enables extended substitution pattern syntax with support
::: for the following escape sequences within the Replace string:
:::
::: \ - Backslash
::: b - Backspace
::: f - Formfeed
::: n - Newline
::: q - Quote
::: r - Carriage Return
::: t - Horizontal Tab
::: v - Vertical Tab
::: xnn - Extended ASCII byte code expressed as 2 hex digits
::: unnnn - Unicode character expressed as 4 hex digits
:::
::: Also enables the q escape sequence for the Search string.
::: The other escape sequences are already standard for a regular
::: expression Search string.
:::
::: Also modifies the behavior of xnn in the Search string to work
::: properly with extended ASCII byte codes.
:::
::: Extended escape sequences are supported even when the L option
::: is used. Both Search and Replace support all of the extended
::: escape sequences if both the X and L opions are combined.
:::
::: Return Codes: 0 = At least one change was made
::: or the /? or /V option was used
:::
::: 1 = No change was made
:::
::: 2 = Invalid call syntax or incompatible options
:::
::: 3 = JScript runtime error, typically due to invalid regex
:::
::: REPL.BAT was written by Dave Benham, with assistance from DosTips user Aacini
::: to get xnn to work properly with extended ASCII byte codes. Also assistance
::: from DosTips user penpen diagnosing issues reading NULL bytes, along with a
::: workaround. REPL.BAT was originally posted at:
::: http://www.dostips.com/forum/viewtopic.php?f=3&t=3855
:::
::************ Batch portion ***********
@echo off
if .%2 equ . (
if "%~1" equ "/?" (
<"%~f0" cscript //E:JScript //nologo "%~f0" "^:::" "" a
exit /b 0
) else if /i "%~1" equ "/?regex" (
explorer "http://msdn.microsoft.com/en-us/library/ae5bf541(v=vs.80).aspx"
exit /b 0
) else if /i "%~1" equ "/?replace" (
explorer "http://msdn.microsoft.com/en-US/library/efy6s3e6(v=vs.80).aspx"
exit /b 0
) else if /i "%~1" equ "/V" (
<"%~f0" cscript //E:JScript //nologo "%~f0" "^::(REPL.BAT version)" "$1" a
exit /b 0
) else (
call :err "Insufficient arguments"
exit /b 2
)
)
echo(%~3|findstr /i "[^SMILEBVXAJ]" >nul && (
call :err "Invalid option(s)"
exit /b 2
)
echo(%~3|findstr /i "M"|findstr /i "A"|findstr /vi "S" >nul && (
call :err "Incompatible options"
exit /b 2
)
cscript //E:JScript //nologo "%~f0" %*
exit /b %errorlevel%
:err
>&2 echo ERROR: %~1. Use REPL /? to get help.
exit /b
************* JScript portion **********/
var rtn=1;
try {
var env=WScript.CreateObject("WScript.Shell").Environment("Process");
var args=WScript.Arguments;
var search=args.Item(0);
var replace=args.Item(1);
var options="g";
if (args.length>2) options+=args.Item(2).toLowerCase();
var multi=(options.indexOf("m")>=0);
var alterations=(options.indexOf("a")>=0);
if (alterations) options=options.replace(/a/g,"");
var srcVar=(options.indexOf("s")>=0);
if (srcVar) options=options.replace(/s/g,"");
var jexpr=(options.indexOf("j")>=0);
if (jexpr) options=options.replace(/j/g,"");
if (options.indexOf("v")>=0) {
options=options.replace(/v/g,"");
search=env(search);
replace=env(replace);
}
if (options.indexOf("x")>=0) {
options=options.replace(/x/g,"");
if (!jexpr) {
replace=replace.replace(/\\/g,"\B");
replace=replace.replace(/\q/g,""");
replace=replace.replace(/\x80/g,"\u20AC");
replace=replace.replace(/\x82/g,"\u201A");
replace=replace.replace(/\x83/g,"\u0192");
replace=replace.replace(/\x84/g,"\u201E");
replace=replace.replace(/\x85/g,"\u2026");
replace=replace.replace(/\x86/g,"\u2020");
replace=replace.replace(/\x87/g,"\u2021");
replace=replace.replace(/\x88/g,"\u02C6");
replace=replace.replace(/\x89/g,"\u2030");
replace=replace.replace(/\x8[aA]/g,"\u0160");
replace=replace.replace(/\x8[bB]/g,"\u2039");
replace=replace.replace(/\x8[cC]/g,"\u0152");
replace=replace.replace(/\x8[eE]/g,"\u017D");
replace=replace.replace(/\x91/g,"\u2018");
replace=replace.replace(/\x92/g,"\u2019");
replace=replace.replace(/\x93/g,"\u201C");
replace=replace.replace(/\x94/g,"\u201D");
replace=replace.replace(/\x95/g,"\u2022");
replace=replace.replace(/\x96/g,"\u2013");
replace=replace.replace(/\x97/g,"\u2014");
replace=replace.replace(/\x98/g,"\u02DC");
replace=replace.replace(/\x99/g,"\u2122");
replace=replace.replace(/\x9[aA]/g,"\u0161");
replace=replace.replace(/\x9[bB]/g,"\u203A");
replace=replace.replace(/\x9[cC]/g,"\u0153");
replace=replace.replace(/\x9[dD]/g,"\u009D");
replace=replace.replace(/\x9[eE]/g,"\u017E");
replace=replace.replace(/\x9[fF]/g,"\u0178");
replace=replace.replace(/\b/g,"b");
replace=replace.replace(/\f/g,"f");
replace=replace.replace(/\n/g,"n");
replace=replace.replace(/\r/g,"r");
replace=replace.replace(/\t/g,"t");
replace=replace.replace(/\v/g,"v");
replace=replace.replace(/\x[0-9a-fA-F]{2}|\u[0-9a-fA-F]{4}/g,
function($0,$1,$2){
return String.fromCharCode(parseInt("0x"+$0.substring(2)));
}
);
replace=replace.replace(/\B/g,"\");
}
search=search.replace(/\\/g,"\B");
search=search.replace(/\q/g,""");
search=search.replace(/\x80/g,"\u20AC");
search=search.replace(/\x82/g,"\u201A");
search=search.replace(/\x83/g,"\u0192");
search=search.replace(/\x84/g,"\u201E");
search=search.replace(/\x85/g,"\u2026");
search=search.replace(/\x86/g,"\u2020");
search=search.replace(/\x87/g,"\u2021");
search=search.replace(/\x88/g,"\u02C6");
search=search.replace(/\x89/g,"\u2030");
search=search.replace(/\x8[aA]/g,"\u0160");
search=search.replace(/\x8[bB]/g,"\u2039");
search=search.replace(/\x8[cC]/g,"\u0152");
search=search.replace(/\x8[eE]/g,"\u017D");
search=search.replace(/\x91/g,"\u2018");
search=search.replace(/\x92/g,"\u2019");
search=search.replace(/\x93/g,"\u201C");
search=search.replace(/\x94/g,"\u201D");
search=search.replace(/\x95/g,"\u2022");
search=search.replace(/\x96/g,"\u2013");
search=search.replace(/\x97/g,"\u2014");
search=search.replace(/\x98/g,"\u02DC");
search=search.replace(/\x99/g,"\u2122");
search=search.replace(/\x9[aA]/g,"\u0161");
search=search.replace(/\x9[bB]/g,"\u203A");
search=search.replace(/\x9[cC]/g,"\u0153");
search=search.replace(/\x9[dD]/g,"\u009D");
search=search.replace(/\x9[eE]/g,"\u017E");
search=search.replace(/\x9[fF]/g,"\u0178");
if (options.indexOf("l")>=0) {
search=search.replace(/\b/g,"b");
search=search.replace(/\f/g,"f");
search=search.replace(/\n/g,"n");
search=search.replace(/\r/g,"r");
search=search.replace(/\t/g,"t");
search=search.replace(/\v/g,"v");
search=search.replace(/\x[0-9a-fA-F]{2}|\u[0-9a-fA-F]{4}/g,
function($0,$1,$2){
return String.fromCharCode(parseInt("0x"+$0.substring(2)));
}
);
search=search.replace(/\B/g,"\");
} else search=search.replace(/\B/g,"\\");
}
if (options.indexOf("l")>=0) {
options=options.replace(/l/g,"");
search=search.replace(/([.^$*+?()[{\|])/g,"\$1");
if (!jexpr) replace=replace.replace(/$/g,"$$$$");
}
if (options.indexOf("b")>=0) {
options=options.replace(/b/g,"");
search="^"+search
}
if (options.indexOf("e")>=0) {
options=options.replace(/e/g,"");
search=search+"$"
}
var search=new RegExp(search,options);
var str1, str2;
if (srcVar) {
str1=env(args.Item(3));
str2=str1.replace(search,jexpr?replFunc:replace);
if (!alterations || str1!=str2) if (multi) {
WScript.Stdout.Write(str2);
} else {
WScript.Stdout.WriteLine(str2);
}
if (str1!=str2) rtn=0;
} else if (multi){
var buf=1024;
str1="";
while (!WScript.StdIn.AtEndOfStream) {
str1+=WScript.StdIn.Read(buf);
buf*=2
}
str2=str1.replace(search,jexpr?replFunc:replace);
WScript.Stdout.Write(str2);
if (str1!=str2) rtn=0;
} else {
while (!WScript.StdIn.AtEndOfStream) {
str1=WScript.StdIn.ReadLine();
str2=str1.replace(search,jexpr?replFunc:replace);
if (!alterations || str1!=str2) WScript.Stdout.WriteLine(str2);
if (str1!=str2) rtn=0;
}
}
} catch(e) {
WScript.Stderr.WriteLine("JScript runtime error: "+e.message);
rtn=3;
}
WScript.Quit(rtn);
function replFunc($0, $1, $2, $3, $4, $5, $6, $7, $8, $9, $10) {
var $=arguments;
return(eval(replace));
}
IMPORTANT UPDATE
I have ceased development of REPL.BAT, and replaced it with JREPL.BAT. This newer utility has all the same functionality of REPL.BAT, plus much more:
- Unicode UTF-16LE support via native CSCRIPT unicode capabilities, and any other character set (including UTF-8) via ADO.
- Read directly from / write directly to a file: no need for pipes, redirection, or move command.
- Incorporate user supplied JScript
- Translation facility similar to unix tr, only it also supports regex search and JScript replace
- Discard non-matching text
- Prefix output lines with line number
- and more…
As always, full documentation is embedded within the script.
The original trivial solution is now even simpler:
jrepl "foo" "bar" /f test.txt /o -
The current version of JREPL.BAT is available at DosTips. Read all of the subsequent posts in the thread to see examples of usage and a history of the development.
Updated: 12/31/2020 by
Finding and replacing text within a text file can be done using any text editor. Below is a listing of all the major text editors with information on how to replace text.
Replacing text within Notepad
Microsoft Notepad is included with all versions of Windows and can replace text in plain text files. To replace text in Notepad, follow the steps below.
- Open the text file in Notepad.
- Click Edit on the menu bar, then select Replace in the Edit menu.
- Once in the Search and Replace window, enter the text you want to find and the text you want to use as a replacement. See our using search and replace and advanced options section for further information and help.
Tip
Press the keyboard shortcut key Ctrl+H to open the Replace window.
Note
The Replace feature in Notepad is limited. If you need to do more than only replace words, consider a different editor.
Replacing text with WordPad
Microsoft WordPad is included with all versions of Windows and can replace text in plain text files. To replace text in WordPad, follow the steps below.
- Open the text file in WordPad.
- In the Ribbon menu, on the Home tab (shown below), click the Replace option.
- In the Search and Replace window, enter the text you want to find and the text you want to use as a replacement. See our using search and replace and advanced options for further information and help.
Tip
Press the keyboard shortcut key Ctrl+H to open the Replace window.
Note
The Replace feature in WordPad is limited. If you need to do more than only replace words, consider a different editor.
Replacing text in Microsoft Word
To replace text in Microsoft Word, follow the steps below.
- Open the text file in Microsoft Word.
- In the Ribbon menu, on the Home tab, click the Replace option.
- In the Find and Replace window, enter the text you want to find and the text you want to use as a replacement. See our using search and replace and advanced options for further information and help.
Tip
Press the keyboard shortcut key Ctrl+H to open the Replace window.
Tip
Clicking the More button in the Find and Replace window gives additional Search Options as shown in the above picture.
Replacing text with Notepad++
Notepad++ is a powerful free and open-source text editor that supports more options for finding and replacing text than any of the above suggestions. To replace text in Notepad++, follow the steps below.
- Open the text file in Notepad++.
- In the top menu bar, click Search and select Replace.
- In the Replace window, on the Replace tab, enter the text you want to find and the text you want to use as a replacement. See our using search and replace and advanced options for further information and help.
Tip
Press the keyboard shortcut key Ctrl+H to open the Replace window.
Replacing text in TextPad
Although not free for the full program, TextPad is another fantastic text editor with powerful search and replace features. To replace text in TextPad, follow the steps below.
- Open the text file in TextPad.
- In the top menu, click Search and then Replace.
- In the Replace window, enter the text you want to find and the text you want to use as a replacement. See our using search and replace and advanced options for further information and help.
Tip
Press the F8 key to open the Replace window.
Find and replace text in Excel
Tip
The Ctrl+F and Command+F keyboard shortcut keys also work in Microsoft Excel and other spreadsheet programs to open the Find and Replace text box.
In Microsoft Excel, older versions featured the Edit menu, and the Replace option is found in that menu. Newer versions of Excel feature a Ribbon menu, and the Find & Select option is found on the Home tab, at the far right side as shown in the picture.
Once the shortcut key opens or you click the Replace option under Find & Select, a Find and Replace window opens. On the Replace tab, enter the text you want to find and replace in the spreadsheet.
Using Search and Replace and advanced options
After understanding the above basics on how to open the search and replace features, understanding all the capabilities possible can make your searches even more efficient.
The basics
All the replace options have the two basic features shown below.
- Match case makes the search case-sensitive, which is useful for finding searches like Names.
- Match whole word matches the whole search instead of words containing the word. For example, a search for ‘can’ only matches ‘can’ and would not match ‘cannot’ or scan’ in your file.
Wildcard and regular expressions
Programs like Microsoft Word that support wildcards and programs like Notepad++ and TextPad that support regular expressions help perform a search for almost anything imaginable. For example, using regular expressions you can replace text found at the beginning of a line, end of the line, works containing a certain amount of characters, and anything else you need.
Other advanced options
More advanced programs may have the features mentioned below. If your program does not include one of the features below, you need to consider switching programs with these features.
- Use wildcards is a feature found in Word that lets you use wildcards.
- Regular expression is the most powerful feature for finding and replacing text in a file.
- Sounds like (English) is a Word feature to match English sounding words. For example, searching for «color» would find «colour» in your document.
- Match prefix is a Word feature to match the prefix (beginning) of a word.
- Match suffix is a Word feature to match the suffix (end) of a word.
- Ignore punctuation characters is a Word feature to ignore punctuation marks like the single quote in «don’t.»
- Ignore white space characters is a Word feature to ignore spaces in words.
February 8th, 2005
Hey, Scripting Guy! From the command line, how can I use a script to open a file and replace text; for example, how can I replace all instances of “Jim” with “James”?
— JW
Hey, JW. As we’ve found out numerous times when dealing with text files, there is no obvious way to do this; that is, there is no ReplaceText command that can open a text file and find and replace text. Fortunately, this problem is typical of text file questions in one other respect: although there’s no obvious way to carry out the task, we can still find a way to get the job done.
Although we can’t directly search and replace text inside a text file, we can do the next best thing. We can: 1) open up a text file; 2) read the text into a variable; 3) do a search-and-replace on that variable; and 4) re-save the text file. We can even do all that from the command line, although we’ll hold off on that for a moment. Instead, let’s start with a simple script that carries out the search and replace:
Const ForReading = 1 Const ForWriting = 2Set objFSO = CreateObject(“Scripting.FileSystemObject”) Set objFile = objFSO.OpenTextFile(“C:ScriptsText.txt”, ForReading)
strText = objFile.ReadAll objFile.Close strNewText = Replace(strText, “Jim “, “James “)
Set objFile = objFSO.OpenTextFile(“C:ScriptsText.txt”, ForWriting) objFile.WriteLine strNewText objFile.Close
We start off by creating two constants (ForReading and ForWriting), which we’ll use for the two occasions when we’ll open our text file. (Yes, we said two occasions). We create an instance of the FileSystemObject, and then use the OpenTextFile method to open the file C:ScriptsText.txt for reading.
With the file open, we use the ReadAll method to read the contents of the entire file into the variable strText. We then close C:ScriptsText.txt even though we’ll almost immediately reopen it, this time for writing. Seems silly, yes, but that’s the way the FileSystemObject works: you can open a file for reading or you can open a file for writing, but you can’t perform both operations at the same time. (As you should know by now, the FileSystemObject works in mysterious ways.)
Having stored the contents of the file in the variable strText, we then use the VBScript Replace function to replace all instances of Jim with James. That’s what we do in this line of code:
strNewText = Replace(strText, “Jim “, “James “)
Notice that we’re looking for each instance of “Jim ” (Jim followed by a blank space) and replacing those with “James ” (James followed by a blank space). Though hardly foolproof, this gives our script a tiny bit of intelligence; if the script encounters the name Jimmy it won’t try to replace the Jim with James (resulting in Jamesmy). The new file we create – the one where each Jim has been replaced by James – is stored in memory in the variable strNewText.
Next we reopen our file (for writing), call the WriteLine method to write the contents of strNewText to the file, and then close the file a second time. The net effect? If we started off with a text file that looked like this:
Jim Jones Mary Smith Jim Doe Jim Johnson Mary Johnston
we’ll end up with a text file that looks like this:
James Jones Mary Smith James Doe James Johnson Mary Johnston
As for doing this all from the command-line, we simply need to modify the script so that it will accept – in this order – three command-line arguments: the name of the file to open; the text we want to search for; and the text we want to replace. Here’s a script that does just that. Note that we store the command-line arguments in the variables strFileName, strOldText, and strNewText, and we use those variables when opening and saving the text file and when calling the Replace function:
Const ForReading = 1 Const ForWriting = 2strFileName = Wscript.Arguments(0) strOldText = Wscript.Arguments(1) strNewText = Wscript.Arguments(2)
Set objFSO = CreateObject(“Scripting.FileSystemObject”) Set objFile = objFSO.OpenTextFile(strFileName, ForReading)
strText = objFile.ReadAll objFile.Close strNewText = Replace(strText, strOldText, strNewText)
Set objFile = objFSO.OpenTextFile(strFileName, ForWriting) objFile.WriteLine strNewText objFile.Close
To use this revised script (which we’ll call replace.vbs) just type a command similar to this from the command prompt:
cscript replace.vbs “C:ScriptsText.txt” “Jim ” “James ”
What do you do if you have to replace a single word in dozens, or even hundreds or thousands, of text files? You keep calm and download Notepad++ [Broken URL Removed] or Replace Text [No Longer Available]. These two utilities will do the job in seconds.
It’s a dilemma common among developers and programmers. Imagine you’re managing a project with hundreds or thousands of files. When a product name that appears on almost every page changes, you can hardly go through each page to manually search and change the name. No, you’re smarter than that.
You fire up Google, you find this article, and you learn about a solution that only takes seconds.
How to Edit Multiple Files in Bulk
You can either use Notepad++ or a dedicated tool called Replace Text to bulk-edit your files.
Notepad++
First, allow Notepad++ to find the word in all the files you need to edit. Open Notepad++ and go to Search > Find in Files… or press CTRL+SHIFT+F. This opes the Find in Files menu.
Under Find what:, enter the word or phrase that you need to change. Under Replace with:, enter the new word or phrase. Finally, set the Directory: where the affected files are located, so that Notepad++ knows where to search.
You can also use advanced settings, which I’ve outlined further down. When all is set, click Find All if you need to double-check the hits or Replace in Files if you want Notepad++ to immediately apply the changes. Depending on the number of files Notepad++ is searching, this can take a few seconds.
If you went with Find All, you’ll get a list of hits. Remove all the files you don’t want to edit by selecting them and pressing DEL, then right-click the remaining files and choose Open all.
Now go to Search > Replace or press CTRL+H, which will launch the Replace menu. Here you’ll find an option to Replace All in All Opened Documents.
Again, you can make several advanced settings, as explained below.
Advanced Search and Replace Settings in Notepad++
Under Find in Files, you can add Filters to search only in certain file types. For example, add *.doc to search only in DOC files. Likewise, you can search for files with a certain name, regardless of file type. Add *.* to search any file name and type.
When you choose a directory with sub-folders, check In all sub-folders and In hidden folders to search those, too. You might also want to check Match whole word only, so you don’t accidentally edit a partial match.
The Search Mode in both the Find in Files and Replace menus allows you to make advanced searches and replacements. Select Extended if you are using extensions, for example to replace a character with a new line (n). Select Regular expression if you’re using operators to find and replace all matching words or phrases. You can stick with Normal if you’re just replacing text with text.
Replace Text [No Longer Available]
With Replace Text, you can set up a Replace Group to add multiple files and/or directories and multiple replacements.
To start, create a new group. Go to Replace > Add Group, and give your group a name.
Right-click your group and select Add File(s)… to add the files and/or folders you want to edit. In the Files / Folder Properties, select your Source Type, i.e., a single file or folder, then choose the Source File / Folder Path. If you choose to add a folder, you can also include and exclude file types by adding them to the Include File Filter or Exclude File Filter rows. Click OK when you’re done.
To add multiple files or folders, repeat the above step.
Replace Text’s best feature is that you can choose a destination that’s different from the original location. In the File / Folder Properties, switch to the Destination tab and choose your desired Destination File / Folder Path.
Now that you’ve set up your group, it’s time to define your replacements. Select your group and go to Replace > Search/Replace Grid > Advanced Edit… Now you can add the Search Text and Replace Text. Be sure to look in the drop-down menu at the bottom to customize the search and replace options.
Like with Notepad++, you can use advanced search strings and operators. Unlike Notepad++, you can add as many search and replace instances as you like and Replace Text will run through all of them when you run the process.
To make the replacements, go to Replace > Start Replacing or press CTRL+R.
What Is Notepad++?
Notepad++ is a free source code editor and Windows Notepad alternative. It’s released under a GNU General Public License, making it an open-source tool.
Furthermore, Notepad++ is a lightweight application that conserves resources, which makes it good for the environment:
By optimizing as many routines as possible without losing user friendliness, Notepad++ is trying to reduce the world carbon dioxide emissions. When using less CPU power, the PC can throttle down and reduce power consumption, resulting in a greener environment.
Here’s a small selection of Notepad++ features that make this the perfect tool for writing and editing (code):
-
Numbered lines for easier navigation.
-
Automatic and customizable highlighting and folding of coding syntax.
-
Support for Perl Compatible Regular Expression (PCRE) search-and-replace.
-
Auto-completion that includes word completion, function completion, and function parameters hint.
-
A tabbed interface that lets you work with multiple documents in parallel.
-
Editing of multiple lines at once, using either CTRL+mouse-selection or column editing.
What Is Replace Text?
Replace Text is a whole lot simpler than Notepad++. It does one job: replacing text. Ecobyte, the company behind Replace Text, is mindful of its impact. Hence, the software with a cause comes with an unusual EULA:
Unfortunately, Replace Text is no longer supported and no help file is available in Windows 10. I have covered it anyhow because it offers more advanced features than Notepad++ for this particular application.
Search and Replace Made Easy
One of the two utilities above should do the job for you. If you only have a simple search-and-replace job or if the additional features of Notepad++ sound useful, you should give it a try. If you need to edit not only multiple files, but also need to make multiple different replacements, it’s worth looking into Replace Text.
Which one did you choose and did it work as prescribed? Have you found other tools that can search-and-replace text? Let us know in the comments below!
Image Credit: Fabrik Bilder via Shutterstock.com
POWERSHELL
Example PowerShell syntax below for find and replacement of strings within a specific file.
EXAMPLE
(Get-Content "C:UsersuserDesktoptesttestzzz.txt") |
Foreach-Object {$_.replace("\changeme", "\servershare name")} |
Set-Content "C:UsersuserDesktoptesttestzzz.txt"
Resources:
- http://ss64.com/ps/replace.html
- http://blogs.technet.com/b/heyscriptingguy/archive/2008/01/17/how-can-i-use-windows-powershell-to-replace-characters-in-a-text-file.aspx
F.A.R.T
For the F.A.R.T issue with spaces specifically, I think you just need to add double-quotes around the strings you’re passing to it. Give that a shot and then perhaps you can just continue to keep using it without further change.
EXAMPLE
"%~dp0Softwarefart" -i -r "%~dp0Softwareconfig.cfg" "\changeme" "%N%"
You can also add the capital -V
switch (see below example) to get verbose detail of the error message if needed to troubleshoot further, but I’ve resolved this issue with F.A.R.T and a space in a replacement string by adding the double-quotes around it as in my below example #2.
Example #2
fart -i -C -V "C:UsersuserDesktoptesttestzzz.txt" "\changeme" "\servershare name"
You also may want to consider excluding the -r
option if you’re only changing the text in a SINGLE file (i.e. config.cfg). Below is the FART /?
options I see exaplaining the options.
Usage: FART [options] [--] <wildcard>[,...] [find_string] [replace_string]
Options:
-h, --help Show this help message (ignores other options)
-q, --quiet Suppress output to stdio / stderr
-V, --verbose Show more information
-r, --recursive Process sub-folders recursively
-c, --count Only show filenames, match counts and totals
-i, --ignore-case Case insensitive text comparison
-v, --invert Print lines NOT containing the find string
-n, --line-number Print line number before each line (1-based)
-w, --word Match whole word (uses C syntax, like grep)
-f, --filename Find (and replace) filename instead of contents
-B, --binary Also search (and replace) in binary files (CAUTION)
-C, --c-style Allow C-style extended characters (xFFtnr\ etc.)
--cvs Skip cvs dirs; execute "cvs edit" before changing files
--svn Skip svn dirs
--remove Remove all occurences of the find_string
-a, --adapt Adapt the case of replace_string to found string
-b, --backup Make a backup of each changed file
-p, --preview Do not change the files but print the changes
Задача замены строки или её части в текстовом файле в командной строке или в bat файле может быть решена различными способами, в зависимости от требований.
Варианты замены текста из командной строки
Утилита поиска и замены текста
Специализированный инструмент всегда даёт самый функциональный и быстрый для реализации способ: готовые утилиты поддерживают все кодировки файлов, имеют опции для разных вариантов замены, поддерживают регулярные выражения и не требуют отладки!
Единственная ситуация, когда вариант с готовой утилитой может не подойти – если есть непреодолимое требование не использовать нестандартные (не входящие в состав Windows) компоненты при развёртывании на большое число корпоративных компьютеров. Но такое встречается нечасто.
Поэтому применение готового, отлаженного и протестированного инструмента является предпочтительным вариантом!
Скрипт на JS или VBS
Возможности VBScript/JScript позволяют реализовать различные варианты замены, включая поддержку регулярных выражений, но всё-таки имеют ограниченные возможности: поддержку меньшего числа кодировок файлов, отсутствие массовой замены, отсутствие подкаталогов и т.д. Любое изменение необходимо отлаживать и тестировать. В общем, очередной «велосипед».
Вариант со скриптом оптимально использовать в случае, когда по каким-то причинам нельзя использовать готовую утилиту.
Bat файлы
О серьёзных возможностях программирования bat файлов говорить не приходится – собственно, bat файл потому и называется пакетным файлом, что предназначен для запуска списка команд по очереди, а не для программирования циклов и обработки переменных.
Сильные стороны bat файлов – удобная форма запуска команд по списку, простое перенаправление вывода и использование переменных окружения, но лучше в bat файлах не программировать.
Ладно раньше, когда предустановленной альтернативы не было, но сейчас, когда на всех компьютерах есть WSH с VBScript/JScript и PowerShell…
Замена текста в файле скриптом JScript
Чтобы сделать замену текста в текстовом файле, в том числе, с использованием регулярных выражений, можно использовать следующий скрипт JScript, который:
- открывает указанный текстовый файл
- читает его построчно
- для каждой строки выполняет замену по регулярному выражению
Код скрипта замены текста
// Имя файла, искомый текст и текст замены берём из аргументов var file_name = WScript.Arguments(0); var text_sample = WScript.Arguments(1); var text_replace = WScript.Arguments(2); var fso=WScript.CreateObject("Scripting.FileSystemObject"); // Переносим исходный файл во временный var file_name_tmp = file_name+".tmp"; if (fso.FileExists(file_name_tmp)) fso.DeleteFile(file_name_tmp); fso.MoveFile(file_name,file_name_tmp); var fo = fso.OpenTextFile(file_name_tmp,1,false,false); var fr = fso.OpenTextFile(file_name,2,true,false); // Выполняем замену текста, с построчной обработкой var re=new RegExp(text_sample); while (!fo.AtEndOfStream) { var line = fo.ReadLine(); var line_replace = line.replace(re,text_replace); fr.WriteLine(line_replace); } fo.Close(); fr.Close(); // Удаляем временный файл fso.DeleteFile(file_name_tmp);
Запуск скрипта замены текста
При запуске скрипта необходимо параметрами передать имя файла, строку поиска (регулярное выражение), строку замены:
cscript //nologo replace_text.js content.txt Foo Bar
Примечания к скрипту
Скрипт обрабатывает файлы в ANSI кодировке. Для Unicode файла необходимо заменить 4-й аргумент в вызовах OpenTextFile c false на true.
Поскольку обработка ведётся по строкам, то регулярные выражения сработают только в пределах одной строки.
Примеры использования скрипта replace-text-script-samples.zip
Замена текста программой nhrt
Больше возможностей и гибкости: поддержка всех кодировок файлов с автоматическим определением, пакетная обработка и многое другое в программе nhrt.
- Use Batch Script To Replace Text From the File
- Use Windows PowerShell To Replace Text From the File
In this article, we will introduce some methods through which you can replace texts in a file. We are going to see two different ways.
Our first method contains only the batch script to perform the task and the second method provides the solution by Windows PowerShell.
Suppose we have a text file with the content below.
Test.txt
:
This is text that is saved in a text file. This is an update. ,,,,,,,,,,,,
We are going to replace these commands with empty characters.
Use Batch Script To Replace Text From the File
Batch Script:
@echo off
FOR /f "tokens=*" %%s IN (Test.txt) DO (
SET Texts=%%s
)
set Texts=%Texts:,=%
FOR /F "tokens=* delims=" %%x IN (Test.txt) DO SET text=%%x
ECHO %Texts% > "G:BATCHTest.txt" :: the path location of the txt file
We first read the file using the line FOR /f "tokens=*" %%s IN (Test.txt) DO (
and then through the line SET Texts=%%s
, we initialize a string variable with the texts of the file. We replaced each comma with an empty character through the line set Texts=%Texts:,=%
.
Lastly, we put the text into the file again. When we run the code above, we will see changes in our file content below.
This is text that is saved in a text file. This is an update.
Use Windows PowerShell To Replace Text From the File
This method will also provide the same result as our previous method did. In this method, we used PowerShell in our batch script. The example code for this method will look like this,
powershell -Command "(gc Test.txt) -replace ',', '' | Out-File -encoding ASCII Test.txt"
When we run the code, we’ll see changes in our file content below.
This is text that is saved in a text file. This is an update.
Remember that the commands we discussed here are only for the Windows command prompt or CMD environment.
Notepad++ is an excellent light-weight text editor with many useful features. With Notepad++, you can find and replace text in the current file or in multiple files in a folder recursively. You can also find and replace text using regex.
This post has many Notepad++ find & replace examples and other useful Notepad++ tips for different scenarios.
Notepad++: Text file manipulation examples
- Remove Path from the File name in a text file
- Remove File name from Full Path in a text file
- Remove a fixed number of characters from the beginning of each line
- Delete characters that exceed ‘n’ number of characters in a text file
- Remove text after a specific character from each line in a text file
- Remove leading or trailing space from each line in a text file
- Delete blank lines in a text file
- Remove Lines Containing a Word or String in a Text File
- Remove text after ‘n’th occurrence of comma or symbol
- Prefix each line with a word or phrase in a text file
- Suffix each line with a word or phrase in a text file
- Remove duplicate rows in a text file without sorting the rows
- Insert new line (carriage return) at a specific character or string
Remove Path from the File name in a text file
If you have full paths for files in a text file and want to remove the path (i.e., only want the file name), use the following Find & Replace technique:
- Bring up the Replace dialog (Ctrl + H) and use the following replace method:
- In the Find box, type
^.*\
- Set the Search mode to Regular expression
- Leave the Replace box blank.
- Uncheck matches newline
- Click Replace All
::Before::
C:UsersrameshPicturesScreenshotsScreenshot 90.png C:UsersrameshPicturesScreenshotsScreenshot 97.png C:UsersrameshPicturesScreenshotsScreenshot 10.png C:UsersrameshPicturesScreenshotsScreenshot 15.png
::After::
Screenshot 90.png Screenshot 97.png Screenshot 10.png Screenshot 15.png
Remove File name from Full Path in a text file
To remove the file name from a full path, use this search operator:
- Find what:
\[^\]+$
- Replace with: Leave empty
- Set the Search mode to Regular expression
- Uncheck matches newline
- Click Replace All
::Before::
D:ToolsSysinternalsaccesschk.exe D:ToolsSysinternalsAccessEnum.exe D:ToolsNirSoftAddrView.exe D:ToolsOthersactivehotkeys.exe
::After::
D:ToolsSysinternals D:ToolsSysinternals D:ToolsNirSoft D:ToolsOthers
Tip: If you need the trailing slash after the folder path, you can use the following regex search instead.
- Find what:
(.*\).*
- Replace with:
1
Remove a fixed number of characters from the beginning of each line
To remove a fixed number of characters at the beginning of each line in a text file, use this regex search & replace query:
- Find what:
^.{11}(.*)$
- Replace with:
$1
- Set the Search mode to Regular expression
- Uncheck matches newline
- Click Replace All
This deletes the first 11 characters from the starting of each line.
::Before::
File Path: D:ToolsSysinternalsaccesschk.exe File Path: D:ToolsSysinternalsAccessEnum.exe File Path: D:ToolsNirSoftAddrView.exe File Path: D:ToolsOthersactivehotkeys.exe
::After::
D:ToolsSysinternalsaccesschk.exe D:ToolsSysinternalsAccessEnum.exe D:ToolsNirSoftAddrView.exe D:ToolsOthersactivehotkeys.exe
Delete characters that exceed the number of characters
To delete characters that exceed the number of characters in a text file, use this:
- Find what:
^.{19}K.*$
- Replace with: Leave blank
- Set the Search mode to Regular expression
- Uncheck matches newline
- Click Replace All
This deletes the characters that exceed 19 characters in each line.
::Before::
The Quick Brown Fox is lazy The Quick Brown Fox is very cute The Quick Brown Fox jumps over the lazy dog
::After::
The Quick Brown Fox The Quick Brown Fox The Quick Brown Fox
Remove text after a specific character from each line in a text file
To remove text after a specific character — e.g., a hyphen, from each line in a text file, use:
- Find what:
(.+)s*-s*(.+)
- Replace with:
$1
- Set the Search mode to Regular expression
- Uncheck matches newline
- Click Replace All
To remove the text before a character (e.g., hyphen), use $2
in the replace field:
- Find what:
(.+)s*-s*(.+)
- Replace with:
$2
Alternatively, to remove text after a specific character or word, you can use the following, which looks easier:
- Find what:
-.*
- Replace with: leave it empty
- Set the Search mode to Regular expression
- Uncheck matches newline
- Click Replace All
::Before::
accesschk.exe - from Sysinternals AccessEnum.exe - from Sysinternals AddrView.exe - from NirSoft activehotkeys.exe - from another vendor
::After::
accesschk.exe AccessEnum.exe AddrView.exe activehotkeys.exe
You can also use it to remove text after a specific word (e.g., “from”).
- Find what:
from.*
- Replace with: leave it empty
- Set the Search mode to Regular expression
- Uncheck matches newline
- Click Replace All
::Before::
accesschk.exe from Sysinternals AccessEnum.exe from Sysinternals AddrView.exe from NirSoft activehotkeys.exe from another vendor
::After::
accesschk.exe AccessEnum.exe AddrView.exe activehotkeys.exe
Remove leading or trailing space from each line in a text file
To remove the trailing and/or leading whitespace from each line in a text file, use the Blank Operations menu.
From the Edit menu in Notepad++, click Blank Operations
Choose one of the three options:
- Trim Trailing Space
- Trim Leading Space
- Trim Leading and Trailing Space
Delete blank lines in a text file
To delete empty/blank lines in a text file, from the Edit menu in Notepad++, select Line Operations, and click Remove Empty Lines
To also remove lines containing blank characters or white spaces, click Remove Empty Lines (Containing Blank characters) option instead.
::Before:
The Quick Brown Fox is lazy The Quick Brown Fox is very cute The Quick Brown Fox jumps over the lazy dog
::After::
The Quick Brown Fox is lazy The Quick Brown Fox is very cute The Quick Brown Fox jumps over the lazy dog
Delete empty lines only in the selected rows
Note that the above command removes empty lines in the entire text file. To remove empty lines only within the text selection, use this search operator:
- Select the rows where you want to remove empty lines.
- Bring up the Replace dialog (Ctrl + H)
- In the Find what: box, type
nr
- Leave the Replace with: box empty
- Enable the In selection checkbox
- Select Search Mode to Extended
- Click Replace All
That’s it! It deletes the empty rows within the selected rows only rather than the entire file.
Remove text after ‘n’th occurrence of comma or symbol
Suppose you have text in each line delimited by a comma or any other symbol. Example below:
::Before::
------------------------------ name,address,pin,landmark ------------------------------ ramesh,10 san jose avenue,11011,near museum pete,1 sf marg,45089,near childrens park john,7 rcr,11909,near metro station
To remove text after the 3rd occurrence of the comma, use this find and replace search operator:
- Find what:
^([^,]*,[^,]*,[^,]*),.*$
- Replace with:
$1
- Set the Search mode to Regular expression
- Uncheck matches newline
- Click Replace All
::After::
-------------------------- name,address,pin -------------------------- ramesh,10 san jose avenue,11011 pete,1 sf marg,45089 john,7 rcr,11909
Prefix each line with a word or phrase in a text file
To add a word or phrase (prefix) at the beginning of each line in a text file, use the following search & replace operator:
- Find what:
^
- Replace with:
Some word or phrase
- Set the Search mode to Regular expression
- Uncheck matches newline
- Click Replace All
The above can be especially useful when creating a HOSTS file to block a list of certain Ad servers. Use 0.0.0.0
with a trailing space in the Replace with: text box, and click Replace All. This adds the prefix string for each line (Ad server) in the text file.
::Before::
ssp.adriver.ru r.adrolays.de adrotate.se www.adrotate.net adrunnr.com
::After::
0.0.0.0 ssp.adriver.ru 0.0.0.0 r.adrolays.de 0.0.0.0 adrotate.se 0.0.0.0 www.adrotate.net 0.0.0.0 adrunnr.com
Suffix each line with a word or phrase in a text file
To add a word or phrase (suffix) at the end of each line in a text file, use the following search & replace operator:
- Find what:
$
- Replace with:
Some word or phrase
- Set the Search mode to Regular expression
- Uncheck matches newline
- Click Replace All
::Before::
D:ToolsSysinternalsaccesschk.exe D:ToolsSysinternalsAccessEnum.exe D:ToolsSysinternalsProcexp.exe
::After::
D:ToolsSysinternalsaccesschk.exe (your word or phrase here) D:ToolsSysinternalsAccessEnum.exe (your word or phrase here) D:ToolsSysinternalsProcexp.exe (your word or phrase here)
Remove duplicate rows in a text file using Notepad++ without sorting the lines
To remove duplicate rows in a text file using Notepad++ without sorting the rows, use this search and replace operator:
- Find what:
^(.*?)$s+?^(?=.*^1$)
- Replace with: Leave blank
- Set the Search mode to Regular expression
- *Enable* matches newline
- Click Replace All
This removes all the duplicate lines leaving out the original. As a bonus, it also removes blank lines automatically.
Important: You must enable matches newline for this to work. Credits to stema
The above is a brilliant method that doesn’t need sorting of the lines. The duplicate rows can be located anywhere in the text file and they’re not reordered.
::Before::
12345 23456 34567 45678 12345 23456 34567 45678 12345 23456 34567 45678
::After::
12345 23456 34567 45678
Remove consecutive duplicate lines
If the duplicate rows are located immediately after each other, to remove the consecutive duplicate rows, from the Edit menu in Notepad++, click Line Operations, and select Remove Consecutive Duplicate Lines
::Before::
12345 12345 12345 23456 23456 34567 34567 45678 45678
::After::
12345 23456 34567 45678
Insert new line (carriage return) at a specific character or string
To insert a new line (carriage return) after at a specific character or string — e.g., after a Comma, use this search and replace operator:
- Find what:
,
- Replace with:
rn
- Set the Search mode to Extended
- Click Replace All
The above search & replace operation adds a new line wherever the comma appears.
::Before::
Cecilia Chapman,711-2880 Nulla St.,Mankato Mississippi 96522,(257) 563-7401,Iris Watson,P.O. Box 283 8562 Fusce Rd.
::After::
Cecilia Chapman 711-2880 Nulla St. Mankato Mississippi 96522 (257) 563-7401 Iris Watson P.O. Box 283 8562 Fusce Rd.
If you want to retain the trailing comma after every line, use ,rn
in the Replace with: text box.
Example 2:
To insert a new line at a specific string ( named GUID:
), use this example:
- Find what:
GUID:
- Replace with:
rn
- Set the Search mode to Extended
- Click Replace All
::Before::
Documents GUID:{D3162B92-9365-467A-956B-92703ACA08AF} Downloads GUID:{088E3905-0323-4B02-9826-5D99428E115F} Music GUID:{3DFDF296-DBEC-4FB4-81D1-6A3438BCF4DE} Pictures GUID:{24AD3AD4-A569-4530-98E1-AB02F9417AA8} Videos GUID:{F86FA3AB-70D2-4FC7-9C99-FCBF05467F3A}
::After::
Documents GUID:{D3162B92-9365-467A-956B-92703ACA08AF} Downloads GUID:{088E3905-0323-4B02-9826-5D99428E115F} Music GUID:{3DFDF296-DBEC-4FB4-81D1-6A3438BCF4DE} Pictures GUID:{24AD3AD4-A569-4530-98E1-AB02F9417AA8} Videos GUID:{F86FA3AB-70D2-4FC7-9C99-FCBF05467F3A}
One small request: If you liked this post, please share this?
One «tiny» share from you would seriously help a lot with the growth of this blog.
Some great suggestions:
- Pin it!
- Share it to your favorite blog + Facebook, Reddit
- Tweet it!
So thank you so much for your support. It won’t take more than 10 seconds of your time. The share buttons are right below.