<p>I am writing a batch file script using Windows command-line environment and want to change each occurrence of some text in a file (ex. "FOO") with another (ex. "BAR"). What is the simplest way to do that? Any built in functions?</p>

[{'answer_id': 60055, 'author': 'Ferruccio', 'author_id': 4086, 'author_profile': 'https://Stackoverflow.com/users/4086', 'pm_score': 5, 'selected': False, 'text': '<p>I don\'t think there\'s a way to do it with any built-in commands. I would suggest you download something like <a href="http://gnuwin32.sourceforge.net/" rel="noreferrer">Gnuwin32</a> or <a href="http://unxutils.sourceforge.net/" rel="noreferrer">UnxUtils</a> and use the <code>sed</code> command (or download only <a href="http://gnuwin32.sourceforge.net/packages/sed.htm" rel="noreferrer"><code>sed</code></a>):</p>\n\n<pre><code>sed -c s/FOO/BAR/g filename\n</code></pre>\n'}, {'answer_id': 60065, 'author': 'Mike Schall', 'author_id': 4231, 'author_profile': 'https://Stackoverflow.com/users/4231', 'pm_score': 8, 'selected': False, 'text': '<p>If you are on Windows version that supports .Net 2.0, I would replace your shell.  <a href="http://en.wikipedia.org/wiki/Windows_PowerShell" rel="noreferrer">PowerShell</a> gives you the full power of .Net from the command line.  There are many commandlets built in as well.  The example below will solve your question.  I\'m using the full names of the commands, there are shorter aliases, but this gives you something to Google for.</p>\n\n<pre><code>(Get-Content test.txt) | ForEach-Object { $_ -replace "foo", "bar" } | Set-Content test2.txt\n</code></pre>\n'}, {'answer_id': 60084, 'author': 'jm.', 'author_id': 814, 'author_profile': 'https://Stackoverflow.com/users/814', 'pm_score': 0, 'selected': False, 'text': '<p>Download <a href="http://www.cygwin.com/" rel="nofollow noreferrer">Cygwin</a> (free) and use unix-like commands at the Windows command line.</p>\n\n<p>Your best bet: sed</p>\n'}, {'answer_id': 64816, 'author': 'morechilli', 'author_id': 5427, 'author_profile': 'https://Stackoverflow.com/users/5427', 'pm_score': 6, 'selected': False, 'text': '<p><a href="http://www.dostips.com/DtCodeBatchFiles.php#Batch.FindAndReplace" rel="noreferrer"><code>BatchSubstitute.bat</code> on dostips.com</a> is an example of search and replace using a pure batch file.</p>\n<p>It uses a combination of <code>FOR</code>, <code>FIND</code> and <code>CALL SET</code>.</p>\n<p>Lines containing characters among <code>&quot;&amp;&lt;&gt;]|^</code> may be treated incorrectly.</p>\n<hr />\n'}, {'answer_id': 85886, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>This is one thing that batch scripting just does not do well.</p>\n\n<p>The script <strong>morechilli</strong> linked to will work for some files, but unfortunately it will choke on ones which contain characters such as pipes and ampersands.</p>\n\n<p>VBScript is a better built-in tool for this task.  See this article for an example:\n<a href="http://www.microsoft.com/technet/scriptcenter/resources/qanda/feb05/hey0208.mspx" rel="nofollow noreferrer">http://www.microsoft.com/technet/scriptcenter/resources/qanda/feb05/hey0208.mspx</a></p>\n'}, {'answer_id': 202635, 'author': 'Jay', 'author_id': 20840, 'author_profile': 'https://Stackoverflow.com/users/20840', 'pm_score': 3, 'selected': False, 'text': '<p>Take a look at <a href="https://stackoverflow.com/questions/127318/">Is there any sed like utility for cmd.exe</a> which asked for a sed equivalent under Windows, should apply to this question as well. Executive summary: </p>\n\n<ul>\n<li>It can be done in batch file, but it\'s not pretty</li>\n<li>Lots of available third party executables that will do it for you, if you have the luxury of installing or just copying over an exe</li>\n<li>Can be done with VBScript or similar if you need something able to run on a Windows box without modification etc.</li>\n</ul>\n'}, {'answer_id': 1953773, 'author': 'Peter Schuetze', 'author_id': 204042, 'author_profile': 'https://Stackoverflow.com/users/204042', 'pm_score': 2, 'selected': False, 'text': '<p>May be a little bit late, but I am frequently looking for similar stuff, since I don\'t want to get through the pain of getting software approved.</p>\n\n<p>However, you usually use the FOR statement in various forms. Someone created a useful batch file that does a search and replace. Have a look <a href="http://www.dostips.com/?t=Batch.FindAndReplace" rel="nofollow noreferrer">here</a>. It is important to understand the limitations of the batch file provided. For this reason I don\'t copy the source code in this answer.</p>\n'}, {'answer_id': 2363075, 'author': 'VonC', 'author_id': 6309, 'author_profile': 'https://Stackoverflow.com/users/6309', 'pm_score': 8, 'selected': False, 'text': '<p>Just used <strong><a href="http://fart-it.sourceforge.net/" rel="noreferrer">FART</a></strong> (&quot;<strong>F</strong> ind <strong>A</strong> nd <strong>R</strong> eplace <strong>T</strong> ext&quot; command line utility):<br />\nexcellent little freeware for text replacement within a large set of files.</p>\n<p>The setup files <a href="http://sourceforge.net/projects/fart-it/files/" rel="noreferrer">are on SourceForge</a>.</p>\n<p>Usage example:</p>\n<pre><code>fart.exe -p -r -c -- C:\\tools\\perl-5.8.9\\* @@APP_DIR@@ C:\\tools\n</code></pre>\n<p>will preview the replacements to do recursively in the files of this Perl distribution.</p>\n<p>Only problem: the FART website icon isn\'t exactly tasteful, refined or elegant ;)</p>\n<hr />\n<p>Update 2017 (7 years later) <a href="https://stackoverflow.com/users/3217130/jagb">jagb</a> points out <a href="https://stackoverflow.com/questions/60034/how-can-you-find-and-replace-text-in-a-file-using-the-windows-command-line-envir/2363075#comment72538743_2363075">in the comments</a> to the 2011 article &quot;<a href="https://emtunc.org/blog/03/2011/farting-the-easy-way-find-and-replace-text/" rel="noreferrer">FARTing the Easy Way – Find And Replace Text</a>&quot; from <a href="https://emtunc.org/blog/about/" rel="noreferrer">Mikail Tunç</a></p>\n<hr />\n<p>As noted by <a href="https://stackoverflow.com/users/7058553/joe-jobs">Joe Jobs</a> in <a href="https://stackoverflow.com/questions/60034/how-can-you-find-and-replace-text-in-a-file-using-the-windows-command-line-envir/2363075?noredirect=1#comment115826648_2363075">the comments</a> (Dec. 2020), if you want to replace <code>&amp;A</code> for instance, you would need to use quotes in order to make sure <code>&amp;</code> is not interpreted by the shell:</p>\n<pre><code>fart in.txt &quot;&amp;A&quot; &quot;B&quot; \n</code></pre>\n'}, {'answer_id': 2419322, 'author': 'Chad', 'author_id': 290782, 'author_profile': 'https://Stackoverflow.com/users/290782', 'pm_score': 3, 'selected': False, 'text': '<p>Here\'s a solution that I found worked on Win XP. In my running batch file, I included the following:</p>\n\n<pre><code>set value=new_value\n\n:: Setup initial configuration\n:: I use &amp;&amp; as the delimiter in the file because it should not exist, thereby giving me the whole line\n::\necho --&gt; Setting configuration and properties.\nfor /f "tokens=* delims=&amp;&amp;" %%a in (config\\config.txt) do ( \n  call replace.bat "%%a" _KEY_ %value% config\\temp.txt \n)\ndel config\\config.txt\nrename config\\temp.txt config.txt\n</code></pre>\n\n<p>The <code>replace.bat</code> file is as below. I did not find a way to include that function within the same batch file, because the <code>%%a</code> variable always seems to give the last value in the for loop.</p>\n\n<p><code>replace.bat</code>:</p>\n\n<pre><code>@echo off\n\n:: This ensures the parameters are resolved prior to the internal variable\n::\nSetLocal EnableDelayedExpansion\n\n:: Replaces Key Variables\n::\n:: Parameters:\n:: %1  = Line to search for replacement\n:: %2  = Key to replace\n:: %3  = Value to replace key with\n:: %4  = File in which to write the replacement\n::\n\n:: Read in line without the surrounding double quotes (use ~)\n::\nset line=%~1\n\n:: Write line to specified file, replacing key (%2) with value (%3)\n::\necho !line:%2=%3! &gt;&gt; %4\n\n:: Restore delayed expansion\n::\nEndLocal\n</code></pre>\n'}, {'answer_id': 3309448, 'author': 'kool_guy_here', 'author_id': 399147, 'author_profile': 'https://Stackoverflow.com/users/399147', 'pm_score': 3, 'selected': False, 'text': '<p>Power shell command works like a charm</p>\n\n<pre><code>(\ntest.txt | ForEach-Object { $_ -replace "foo", "bar" } | Set-Content test2.txt\n)\n</code></pre>\n'}, {'answer_id': 3801102, 'author': 'user459118', 'author_id': 459118, 'author_profile': 'https://Stackoverflow.com/users/459118', 'pm_score': 6, 'selected': False, 'text': '<p>Create file replace.vbs:</p>\n\n<pre><code>Const ForReading = 1    \nConst ForWriting = 2\n\nstrFileName = Wscript.Arguments(0)\nstrOldText = Wscript.Arguments(1)\nstrNewText = Wscript.Arguments(2)\n\nSet objFSO = CreateObject("Scripting.FileSystemObject")\nSet objFile = objFSO.OpenTextFile(strFileName, ForReading)\nstrText = objFile.ReadAll\nobjFile.Close\n\nstrNewText = Replace(strText, strOldText, strNewText)\nSet objFile = objFSO.OpenTextFile(strFileName, ForWriting)\nobjFile.Write strNewText  \'WriteLine adds extra CR/LF\nobjFile.Close\n</code></pre>\n\n<p>To use this revised script (which we’ll call replace.vbs) just type a command similar to this from the command prompt:</p>\n\n<p><code>cscript replace.vbs "C:\\Scripts\\Text.txt" "Jim " "James "</code></p>\n'}, {'answer_id': 4402290, 'author': 'Faisal', 'author_id': 536948, 'author_profile': 'https://Stackoverflow.com/users/536948', 'pm_score': 4, 'selected': False, 'text': '<p>I have used perl, and that works marvelously.</p>\n\n<pre><code>perl -pi.orig -e "s/&lt;textToReplace&gt;/&lt;textToReplaceWith&gt;/g;" &lt;fileName&gt;\n</code></pre>\n\n<p>.orig is the extension it would append to the original file</p>\n\n<p>For a number of files matching  such as *.html</p>\n\n<pre><code>for %x in (&lt;filePattern&gt;) do perl -pi.orig -e "s/&lt;textToReplace&gt;/&lt;textToReplaceWith&gt;/g;" %x\n</code></pre>\n'}, {'answer_id': 6159108, 'author': 'Bill Richardson', 'author_id': 773948, 'author_profile': 'https://Stackoverflow.com/users/773948', 'pm_score': 7, 'selected': False, 'text': '<p>Replace - Replace a substring using string substitution\nDescription: To replace a substring with another string use the string substitution feature. The example shown here replaces all occurrences "teh" misspellings with "the" in the string variable str. </p>\n\n<pre><code>set str=teh cat in teh hat\necho.%str%\nset str=%str:teh=the%\necho.%str%\n</code></pre>\n\n<p>Script Output:     </p>\n\n<pre><code>teh cat in teh hat\nthe cat in the hat\n</code></pre>\n\n<p>ref:  <a href="http://www.dostips.com/DtTipsStringManipulation.php#Snippets.Replace" rel="noreferrer">http://www.dostips.com/DtTipsStringManipulation.php#Snippets.Replace</a></p>\n'}, {'answer_id': 10490757, 'author': 'Simon East', 'author_id': 195835, 'author_profile': 'https://Stackoverflow.com/users/195835', 'pm_score': 4, 'selected': False, 'text': '<p>I played around with some of the existing answers here and prefer my improved solution...</p>\n\n<pre><code>type test.txt | powershell -Command "$input | ForEach-Object { $_ -replace \\"foo\\", \\"bar\\" }"\n</code></pre>\n\n<p>or if you want to save the output again to a file...</p>\n\n<pre><code>type test.txt | powershell -Command "$input | ForEach-Object { $_ -replace \\"foo\\", \\"bar\\" }" &gt; outputFile.txt\n</code></pre>\n\n<p>The benefit of this is that you can pipe in output from any program.  Will look into using regular expressions with this too.  Couldn\'t work out how to make it into a BAT file for easier use though... :-(</p>\n'}, {'answer_id': 14396154, 'author': 'Aman', 'author_id': 173136, 'author_profile': 'https://Stackoverflow.com/users/173136', 'pm_score': 5, 'selected': False, 'text': '<h1>Use FNR</h1>\n<p>Use the <code>fnr</code> utility. It\'s got some advantages over <code>fart</code>:</p>\n<ul>\n<li>Regular expressions</li>\n<li>Optional GUI. Has a &quot;Generate command line button&quot; to create command line text to put in batch file.</li>\n<li>Multi-line patterns: The GUI allows you to easily work with multi-line patterns. In FART you\'d have to manually escape line breaks.</li>\n<li>Allows you to select text file encoding. Also has an auto detect option.</li>\n</ul>\n<p>Download FNR here: <a href="http://findandreplace.io/?z=codeplex" rel="noreferrer">http://findandreplace.io/?z=codeplex</a></p>\n<p>Usage example:\n<code>fnr --cl --dir &quot;&lt;Directory Path&gt;&quot; --fileMask &quot;hibernate.*&quot;  --useRegEx --find &quot;find_str_expression&quot; --replace &quot;replace_string&quot;</code></p>\n'}, {'answer_id': 16735079, 'author': 'dbenham', 'author_id': 1012053, 'author_profile': 'https://Stackoverflow.com/users/1012053', 'pm_score': 6, 'selected': False, 'text': '<p><strong><em>Note</em></strong> <em>- Be sure to see the update at the end of this answer for a link to the superior JREPL.BAT that supersedes REPL.BAT</em><br>\n<em><a href="http://www.dostips.com/forum/viewtopic.php?f=3&amp;t=6044" rel="noreferrer">JREPL.BAT 7.0 and above</a> natively supports unicode (UTF-16LE) via the <code>/UTF</code> option, as well as any other character set, including UTF-8, via ADO!!!!</em></p>\n\n<hr>\n\n<p><a href="http://www.dostips.com/forum/viewtopic.php?f=3&amp;t=3855" rel="noreferrer">I have written a small hybrid JScript/batch utility called REPL.BAT</a> 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.</p>\n\n<p>REPL.BAT simply reads stdin, performs a JScript regex search and replace, and writes the result to stdout.</p>\n\n<p>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:</p>\n\n<pre><code>type test.txt|repl "foo" "bar" &gt;test.txt.new\nmove /y test.txt.new test.txt\n</code></pre>\n\n<p>The JScript regex capabilities make it very powerful, especially the ability of the replacement text to reference captured substrings from the search text.</p>\n\n<p>I\'ve included a number of options in the utility that make it quite powerful. For example, combining the <code>M</code> and <code>X</code> options enable modification of binary files! The <code>M</code> Multi-line option allows searches across multiple lines. The <code>X</code> eXtended substitution pattern option provides escape sequences that enable inclusion of any binary value in the replacement text.</p>\n\n<p>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.</p>\n\n<p>Here is the REPL.BAT script. Full documentation is embedded within the script.</p>\n\n<pre><code>@if (@X)==(@Y) @end /* Harmless hybrid line that begins a JScript comment\n\n::************ Documentation ***********\n::REPL.BAT version 6.2\n:::\n:::REPL  Search  Replace  [Options  [SourceVar]]\n:::REPL  /?[REGEX|REPLACE]\n:::REPL  /V\n:::\n:::  Performs a global regular expression search and replace operation on\n:::  each line of input from stdin and prints the result to stdout.\n:::\n:::  Each parameter may be optionally enclosed by double quotes. The double\n:::  quotes are not considered part of the argument. The quotes are required\n:::  if the parameter contains a batch token delimiter like space, tab, comma,\n:::  semicolon. The quotes should also be used if the argument contains a\n:::  batch special character like &amp;, |, etc. so that the special character\n:::  does not need to be escaped with ^.\n:::\n:::  If called with a single argument of /?, then prints help documentation\n:::  to stdout. If a single argument of /?REGEX, then opens up Microsoft\'s\n:::  JScript regular expression documentation within your browser. If a single\n:::  argument of /?REPLACE, then opens up Microsoft\'s JScript REPLACE\n:::  documentation within your browser.\n:::\n:::  If called with a single argument of /V, case insensitive, then prints\n:::  the version of REPL.BAT.\n:::\n:::  Search  - By default, this is a case sensitive JScript (ECMA) regular\n:::            expression expressed as a string.\n:::\n:::            JScript regex syntax documentation is available at\n:::            http://msdn.microsoft.com/en-us/library/ae5bf541(v=vs.80).aspx\n:::\n:::  Replace - By default, this is the string to be used as a replacement for\n:::            each found search expression. Full support is provided for\n:::            substituion patterns available to the JScript replace method.\n:::\n:::            For example, $&amp; represents the portion of the source that matched\n:::            the entire search pattern, $1 represents the first captured\n:::            submatch, $2 the second captured submatch, etc. A $ literal\n:::            can be escaped as $$.\n:::\n:::            An empty replacement string must be represented as "".\n:::\n:::            Replace substitution pattern syntax is fully documented at\n:::            http://msdn.microsoft.com/en-US/library/efy6s3e6(v=vs.80).aspx\n:::\n:::  Options - An optional string of characters used to alter the behavior\n:::            of REPL. The option characters are case insensitive, and may\n:::            appear in any order.\n:::\n:::            A - Only print altered lines. Unaltered lines are discarded.\n:::                If the S options is present, then prints the result only if\n:::                there was a change anywhere in the string. The A option is\n:::                incompatible with the M option unless the S option is present.\n:::\n:::            B - The Search must match the beginning of a line.\n:::                Mostly used with literal searches.\n:::\n:::            E - The Search must match the end of a line.\n:::                Mostly used with literal searches.\n:::\n:::            I - Makes the search case-insensitive.\n:::\n:::            J - The Replace argument represents a JScript expression.\n:::                The expression may access an array like arguments object\n:::                named $. However, $ is not a true array object.\n:::\n:::                The $.length property contains the total number of arguments\n:::                available. The $.length value is equal to n+3, where n is the\n:::                number of capturing left parentheses within the Search string.\n:::\n:::                $[0] is the substring that matched the Search,\n:::                $[1] through $[n] are the captured submatch strings,\n:::                $[n+1] is the offset where the match occurred, and\n:::                $[n+2] is the original source string.\n:::\n:::                Arguments $[0] through $[10] may be abbreviated as\n:::                $1 through $10. Argument $[11] and above must use the square\n:::                bracket notation.\n:::\n:::            L - The Search is treated as a string literal instead of a\n:::                regular expression. Also, all $ found in the Replace string\n:::                are treated as $ literals.\n:::\n:::            M - Multi-line mode. The entire contents of stdin is read and\n:::                processed in one pass instead of line by line, thus enabling\n:::                search for \\n. This also enables preservation of the original\n:::                line terminators. If the M option is not present, then every\n:::                printed line is terminated with carriage return and line feed.\n:::                The M option is incompatible with the A option unless the S\n:::                option is also present.\n:::\n:::                Note: If working with binary data containing NULL bytes,\n:::                      then the M option must be used.\n:::\n:::            S - The source is read from an environment variable instead of\n:::                from stdin. The name of the source environment variable is\n:::                specified in the next argument after the option string. Without\n:::                the M option, ^ anchors the beginning of the string, and $ the\n:::                end of the string. With the M option, ^ anchors the beginning\n:::                of a line, and $ the end of a line.\n:::\n:::            V - Search and Replace represent the name of environment\n:::                variables that contain the respective values. An undefined\n:::                variable is treated as an empty string.\n:::\n:::            X - Enables extended substitution pattern syntax with support\n:::                for the following escape sequences within the Replace string:\n:::\n:::                \\\\     -  Backslash\n:::                \\b     -  Backspace\n:::                \\f     -  Formfeed\n:::                \\n     -  Newline\n:::                \\q     -  Quote\n:::                \\r     -  Carriage Return\n:::                \\t     -  Horizontal Tab\n:::                \\v     -  Vertical Tab\n:::                \\xnn   -  Extended ASCII byte code expressed as 2 hex digits\n:::                \\unnnn -  Unicode character expressed as 4 hex digits\n:::\n:::                Also enables the \\q escape sequence for the Search string.\n:::                The other escape sequences are already standard for a regular\n:::                expression Search string.\n:::\n:::                Also modifies the behavior of \\xnn in the Search string to work\n:::                properly with extended ASCII byte codes.\n:::\n:::                Extended escape sequences are supported even when the L option\n:::                is used. Both Search and Replace support all of the extended\n:::                escape sequences if both the X and L opions are combined.\n:::\n:::  Return Codes:  0 = At least one change was made\n:::                     or the /? or /V option was used\n:::\n:::                 1 = No change was made\n:::\n:::                 2 = Invalid call syntax or incompatible options\n:::\n:::                 3 = JScript runtime error, typically due to invalid regex\n:::\n::: REPL.BAT was written by Dave Benham, with assistance from DosTips user Aacini\n::: to get \\xnn to work properly with extended ASCII byte codes. Also assistance\n::: from DosTips user penpen diagnosing issues reading NULL bytes, along with a\n::: workaround. REPL.BAT was originally posted at:\n::: http://www.dostips.com/forum/viewtopic.php?f=3&amp;t=3855\n:::\n\n::************ Batch portion ***********\n@echo off\nif .%2 equ . (\n  if "%~1" equ "/?" (\n    &lt;"%~f0" cscript //E:JScript //nologo "%~f0" "^:::" "" a\n    exit /b 0\n  ) else if /i "%~1" equ "/?regex" (\n    explorer "http://msdn.microsoft.com/en-us/library/ae5bf541(v=vs.80).aspx"\n    exit /b 0\n  ) else if /i "%~1" equ "/?replace" (\n    explorer "http://msdn.microsoft.com/en-US/library/efy6s3e6(v=vs.80).aspx"\n    exit /b 0\n  ) else if /i "%~1" equ "/V" (\n    &lt;"%~f0" cscript //E:JScript //nologo "%~f0" "^::(REPL\\.BAT version)" "$1" a\n    exit /b 0\n  ) else (\n    call :err "Insufficient arguments"\n    exit /b 2\n  )\n)\necho(%~3|findstr /i "[^SMILEBVXAJ]" &gt;nul &amp;&amp; (\n  call :err "Invalid option(s)"\n  exit /b 2\n)\necho(%~3|findstr /i "M"|findstr /i "A"|findstr /vi "S" &gt;nul &amp;&amp; (\n  call :err "Incompatible options"\n  exit /b 2\n)\ncscript //E:JScript //nologo "%~f0" %*\nexit /b %errorlevel%\n\n:err\n&gt;&amp;2 echo ERROR: %~1. Use REPL /? to get help.\nexit /b\n\n************* JScript portion **********/\nvar rtn=1;\ntry {\n  var env=WScript.CreateObject("WScript.Shell").Environment("Process");\n  var args=WScript.Arguments;\n  var search=args.Item(0);\n  var replace=args.Item(1);\n  var options="g";\n  if (args.length&gt;2) options+=args.Item(2).toLowerCase();\n  var multi=(options.indexOf("m")&gt;=0);\n  var alterations=(options.indexOf("a")&gt;=0);\n  if (alterations) options=options.replace(/a/g,"");\n  var srcVar=(options.indexOf("s")&gt;=0);\n  if (srcVar) options=options.replace(/s/g,"");\n  var jexpr=(options.indexOf("j")&gt;=0);\n  if (jexpr) options=options.replace(/j/g,"");\n  if (options.indexOf("v")&gt;=0) {\n    options=options.replace(/v/g,"");\n    search=env(search);\n    replace=env(replace);\n  }\n  if (options.indexOf("x")&gt;=0) {\n    options=options.replace(/x/g,"");\n    if (!jexpr) {\n      replace=replace.replace(/\\\\\\\\/g,"\\\\B");\n      replace=replace.replace(/\\\\q/g,"\\"");\n      replace=replace.replace(/\\\\x80/g,"\\\\u20AC");\n      replace=replace.replace(/\\\\x82/g,"\\\\u201A");\n      replace=replace.replace(/\\\\x83/g,"\\\\u0192");\n      replace=replace.replace(/\\\\x84/g,"\\\\u201E");\n      replace=replace.replace(/\\\\x85/g,"\\\\u2026");\n      replace=replace.replace(/\\\\x86/g,"\\\\u2020");\n      replace=replace.replace(/\\\\x87/g,"\\\\u2021");\n      replace=replace.replace(/\\\\x88/g,"\\\\u02C6");\n      replace=replace.replace(/\\\\x89/g,"\\\\u2030");\n      replace=replace.replace(/\\\\x8[aA]/g,"\\\\u0160");\n      replace=replace.replace(/\\\\x8[bB]/g,"\\\\u2039");\n      replace=replace.replace(/\\\\x8[cC]/g,"\\\\u0152");\n      replace=replace.replace(/\\\\x8[eE]/g,"\\\\u017D");\n      replace=replace.replace(/\\\\x91/g,"\\\\u2018");\n      replace=replace.replace(/\\\\x92/g,"\\\\u2019");\n      replace=replace.replace(/\\\\x93/g,"\\\\u201C");\n      replace=replace.replace(/\\\\x94/g,"\\\\u201D");\n      replace=replace.replace(/\\\\x95/g,"\\\\u2022");\n      replace=replace.replace(/\\\\x96/g,"\\\\u2013");\n      replace=replace.replace(/\\\\x97/g,"\\\\u2014");\n      replace=replace.replace(/\\\\x98/g,"\\\\u02DC");\n      replace=replace.replace(/\\\\x99/g,"\\\\u2122");\n      replace=replace.replace(/\\\\x9[aA]/g,"\\\\u0161");\n      replace=replace.replace(/\\\\x9[bB]/g,"\\\\u203A");\n      replace=replace.replace(/\\\\x9[cC]/g,"\\\\u0153");\n      replace=replace.replace(/\\\\x9[dD]/g,"\\\\u009D");\n      replace=replace.replace(/\\\\x9[eE]/g,"\\\\u017E");\n      replace=replace.replace(/\\\\x9[fF]/g,"\\\\u0178");\n      replace=replace.replace(/\\\\b/g,"\\b");\n      replace=replace.replace(/\\\\f/g,"\\f");\n      replace=replace.replace(/\\\\n/g,"\\n");\n      replace=replace.replace(/\\\\r/g,"\\r");\n      replace=replace.replace(/\\\\t/g,"\\t");\n      replace=replace.replace(/\\\\v/g,"\\v");\n      replace=replace.replace(/\\\\x[0-9a-fA-F]{2}|\\\\u[0-9a-fA-F]{4}/g,\n        function($0,$1,$2){\n          return String.fromCharCode(parseInt("0x"+$0.substring(2)));\n        }\n      );\n      replace=replace.replace(/\\\\B/g,"\\\\");\n    }\n    search=search.replace(/\\\\\\\\/g,"\\\\B");\n    search=search.replace(/\\\\q/g,"\\"");\n    search=search.replace(/\\\\x80/g,"\\\\u20AC");\n    search=search.replace(/\\\\x82/g,"\\\\u201A");\n    search=search.replace(/\\\\x83/g,"\\\\u0192");\n    search=search.replace(/\\\\x84/g,"\\\\u201E");\n    search=search.replace(/\\\\x85/g,"\\\\u2026");\n    search=search.replace(/\\\\x86/g,"\\\\u2020");\n    search=search.replace(/\\\\x87/g,"\\\\u2021");\n    search=search.replace(/\\\\x88/g,"\\\\u02C6");\n    search=search.replace(/\\\\x89/g,"\\\\u2030");\n    search=search.replace(/\\\\x8[aA]/g,"\\\\u0160");\n    search=search.replace(/\\\\x8[bB]/g,"\\\\u2039");\n    search=search.replace(/\\\\x8[cC]/g,"\\\\u0152");\n    search=search.replace(/\\\\x8[eE]/g,"\\\\u017D");\n    search=search.replace(/\\\\x91/g,"\\\\u2018");\n    search=search.replace(/\\\\x92/g,"\\\\u2019");\n    search=search.replace(/\\\\x93/g,"\\\\u201C");\n    search=search.replace(/\\\\x94/g,"\\\\u201D");\n    search=search.replace(/\\\\x95/g,"\\\\u2022");\n    search=search.replace(/\\\\x96/g,"\\\\u2013");\n    search=search.replace(/\\\\x97/g,"\\\\u2014");\n    search=search.replace(/\\\\x98/g,"\\\\u02DC");\n    search=search.replace(/\\\\x99/g,"\\\\u2122");\n    search=search.replace(/\\\\x9[aA]/g,"\\\\u0161");\n    search=search.replace(/\\\\x9[bB]/g,"\\\\u203A");\n    search=search.replace(/\\\\x9[cC]/g,"\\\\u0153");\n    search=search.replace(/\\\\x9[dD]/g,"\\\\u009D");\n    search=search.replace(/\\\\x9[eE]/g,"\\\\u017E");\n    search=search.replace(/\\\\x9[fF]/g,"\\\\u0178");\n    if (options.indexOf("l")&gt;=0) {\n      search=search.replace(/\\\\b/g,"\\b");\n      search=search.replace(/\\\\f/g,"\\f");\n      search=search.replace(/\\\\n/g,"\\n");\n      search=search.replace(/\\\\r/g,"\\r");\n      search=search.replace(/\\\\t/g,"\\t");\n      search=search.replace(/\\\\v/g,"\\v");\n      search=search.replace(/\\\\x[0-9a-fA-F]{2}|\\\\u[0-9a-fA-F]{4}/g,\n        function($0,$1,$2){\n          return String.fromCharCode(parseInt("0x"+$0.substring(2)));\n        }\n      );\n      search=search.replace(/\\\\B/g,"\\\\");\n    } else search=search.replace(/\\\\B/g,"\\\\\\\\");\n  }\n  if (options.indexOf("l")&gt;=0) {\n    options=options.replace(/l/g,"");\n    search=search.replace(/([.^$*+?()[{\\\\|])/g,"\\\\$1");\n    if (!jexpr) replace=replace.replace(/\\$/g,"$$$$");\n  }\n  if (options.indexOf("b")&gt;=0) {\n    options=options.replace(/b/g,"");\n    search="^"+search\n  }\n  if (options.indexOf("e")&gt;=0) {\n    options=options.replace(/e/g,"");\n    search=search+"$"\n  }\n  var search=new RegExp(search,options);\n  var str1, str2;\n\n  if (srcVar) {\n    str1=env(args.Item(3));\n    str2=str1.replace(search,jexpr?replFunc:replace);\n    if (!alterations || str1!=str2) if (multi) {\n      WScript.Stdout.Write(str2);\n    } else {\n      WScript.Stdout.WriteLine(str2);\n    }\n    if (str1!=str2) rtn=0;\n  } else if (multi){\n    var buf=1024;\n    str1="";\n    while (!WScript.StdIn.AtEndOfStream) {\n      str1+=WScript.StdIn.Read(buf);\n      buf*=2\n    }\n    str2=str1.replace(search,jexpr?replFunc:replace);\n    WScript.Stdout.Write(str2);\n    if (str1!=str2) rtn=0;\n  } else {\n    while (!WScript.StdIn.AtEndOfStream) {\n      str1=WScript.StdIn.ReadLine();\n      str2=str1.replace(search,jexpr?replFunc:replace);\n      if (!alterations || str1!=str2) WScript.Stdout.WriteLine(str2);\n      if (str1!=str2) rtn=0;\n    }\n  }\n} catch(e) {\n  WScript.Stderr.WriteLine("JScript runtime error: "+e.message);\n  rtn=3;\n}\nWScript.Quit(rtn);\n\nfunction replFunc($0, $1, $2, $3, $4, $5, $6, $7, $8, $9, $10) {\n  var $=arguments;\n  return(eval(replace));\n}\n</code></pre>\n\n<p><br/>\n<strong><em>IMPORTANT UPDATE</em></strong></p>\n\n<p>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: </p>\n\n<ul>\n<li>Unicode UTF-16LE support via native CSCRIPT unicode capabilities, and any other character set (including UTF-8) via ADO.</li>\n<li>Read directly from / write directly to a file: no need for pipes, redirection, or move command.</li>\n<li>Incorporate user supplied JScript</li>\n<li>Translation facility similar to unix tr, only it also supports regex search and JScript replace</li>\n<li>Discard non-matching text</li>\n<li>Prefix output lines with line number</li>\n<li>and more...</li>\n</ul>\n\n<p>As always, full documentation is embedded within the script. </p>\n\n<p>The original trivial solution is now even simpler:</p>\n\n<pre><code>jrepl "foo" "bar" /f test.txt /o -\n</code></pre>\n\n<p><a href="http://www.dostips.com/forum/viewtopic.php?f=3&amp;t=6044" rel="noreferrer">The current version of JREPL.BAT is available at DosTips</a>. Read all of the subsequent posts in the thread to see examples of usage and a history of the development.</p>\n'}, {'answer_id': 20999154, 'author': 'Rachel', 'author_id': 302677, 'author_profile': 'https://Stackoverflow.com/users/302677', 'pm_score': 10, 'selected': True, 'text': "<p>A lot of the answers here helped point me in the right direction, however none were suitable for me, so I am posting my solution.</p>\n<p>I have Windows 7, which comes with PowerShell built-in. Here is the script I used to find/replace all instances of text in a file:</p>\n<pre><code>powershell -Command &quot;(gc myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt&quot;\n</code></pre>\n<p>To explain it:</p>\n<ul>\n<li><code>powershell</code> starts up powershell.exe, which is included in Windows 7</li>\n<li><code>-Command &quot;... &quot;</code> is a command line arg for powershell.exe containing the command to run</li>\n<li><code>(gc myFile.txt)</code> reads the content of <code>myFile.txt</code> (<code>gc</code> is short for the <code>Get-Content</code> command)</li>\n<li><code>-replace 'foo', 'bar'</code> simply runs the replace command to replace <code>foo</code> with <code>bar</code></li>\n<li><code>| Out-File myFile.txt</code> pipes the output to the file <code>myFile.txt</code></li>\n<li><code>-encoding ASCII</code> prevents transcribing the output file to unicode, as the comments point out</li>\n</ul>\n<p>Powershell.exe should be part of your PATH statement already, but if not you can add it. The location of it on my machine is <code>C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0</code></p>\n<p><strong>Update</strong><br/>Apparently modern windows systems have PowerShell built in allowing you to access this directly using</p>\n<pre><code>(Get-Content myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt\n</code></pre>\n"}, {'answer_id': 24887951, 'author': 'foxidrive', 'author_id': 2299431, 'author_profile': 'https://Stackoverflow.com/users/2299431', 'pm_score': 3, 'selected': False, 'text': '<p>Two batch files that supply <code>search and replace</code> functions have been written by Stack Overflow members <code>dbenham</code> and <code>aacini</code> using <code>native built-in jscript</code> in Windows.  </p>\n\n<p>They are both <code>robust</code> and <code>very swift with large files</code> compared to plain batch scripting, and also <code>simpler</code> to use for basic replacing of text.  They both have <code>Windows regular expression</code> pattern matching.</p>\n\n<ol>\n<li><p>This<code>sed-like</code> helper batch file is called <a href="https://www.dostips.com/forum/viewtopic.php?f=3&amp;t=3855" rel="nofollow noreferrer"><code>repl.bat</code></a> (by dbenham).</p>\n\n<p>Example using the <code>L</code> literal switch:</p>\n\n<pre><code>echo This is FOO here|repl "FOO" "BAR" L\necho and with a file:\ntype "file.txt" |repl "FOO" "BAR" L &gt;"newfile.txt"\n</code></pre></li>\n<li><p>This <code>grep-like</code> helper batch file is called <a href="https://www.dostips.com/forum/viewtopic.php?t=4697" rel="nofollow noreferrer"><code>findrepl.bat</code></a> (by aacini).</p>\n\n<p>Example which has regular expressions active:</p>\n\n<pre><code>echo This is FOO here|findrepl "FOO" "BAR" \necho and with a file:\ntype "file.txt" |findrepl "FOO" "BAR" &gt;"newfile.txt"\n</code></pre></li>\n</ol>\n\n<p>Both become powerful system-wide utilities <code>when placed in a folder that is on the path</code>, or can be used in the same folder with a batch file, or from the cmd prompt.</p>\n\n<p>They both have <code>case-insensitive</code> switches and also many other functions.</p>\n'}, {'answer_id': 26894259, 'author': 'Leptonator', 'author_id': 175063, 'author_profile': 'https://Stackoverflow.com/users/175063', 'pm_score': 5, 'selected': False, 'text': '<p>I know I am late to the party..</p>\n\n<p>Personally, I like the solution at:\n - <a href="http://www.dostips.com/DtTipsStringManipulation.php#Snippets.Replace" rel="noreferrer">http://www.dostips.com/DtTipsStringManipulation.php#Snippets.Replace</a></p>\n\n<p>We also, use the Dedupe Function extensively to help us deliver approximately 500 e-mails daily via SMTP from:\n- <a href="https://groups.google.com/forum/#!topic/alt.msdos.batch.nt/sj8IUhMOq6o" rel="noreferrer">https://groups.google.com/forum/#!topic/alt.msdos.batch.nt/sj8IUhMOq6o</a></p>\n\n<p>and these both work natively with no extra tools or utilities needed.</p>\n\n<p>REPLACER:</p>\n\n<pre><code>DEL New.txt\nsetLocal EnableDelayedExpansion\nFor /f "tokens=* delims= " %%a in (OLD.txt) do (\nSet str=%%a\nset str=!str:FOO=BAR!\necho !str!&gt;&gt;New.txt\n)\nENDLOCAL\n</code></pre>\n\n<p>DEDUPLICATOR (note the use of -9 for an ABA number):</p>\n\n<pre><code>REM DE-DUPLICATE THE Mapping.txt FILE\nREM THE DE-DUPLICATED FILE IS STORED AS new.txt\n\nset MapFile=Mapping.txt\nset ReplaceFile=New.txt\n\ndel %ReplaceFile%\n::DelDupeText.bat\nrem https://groups.google.com/forum/#!topic/alt.msdos.batch.nt/sj8IUhMOq6o\nsetLocal EnableDelayedExpansion\nfor /f "tokens=1,2 delims=," %%a in (%MapFile%) do (\nset str=%%a\nrem Ref: http://www.dostips.com/DtTipsStringManipulation.php#Snippets.RightString\nset str=!str:~-9!\nset str2=%%a\nset str3=%%a,%%b\n\nfind /i ^"!str!^" %MapFile%\nfind /i ^"!str!^" %ReplaceFile%\nif errorlevel 1 echo !str3!&gt;&gt;%ReplaceFile%\n)\nENDLOCAL\n</code></pre>\n\n<p>Thanks!</p>\n'}, {'answer_id': 29260513, 'author': 'Nadjib', 'author_id': 4712931, 'author_profile': 'https://Stackoverflow.com/users/4712931', 'pm_score': -1, 'selected': False, 'text': '<p>I have faced this problem several times while coding under Visual C++.\nIf you have it, you can use Visual studio Find and Replace Utility. It allows you to select a folder and replace the contents of any file in that folder with any other text you want.</p>\n\n<p>Under Visual Studio: \nEdit -> Find and Replace \nIn the opened dialog, select your folder and fill in "Find What" and "Replace With" boxes.\nHope this will be helpful. </p>\n'}, {'answer_id': 31812389, 'author': 'madcorp', 'author_id': 2883841, 'author_profile': 'https://Stackoverflow.com/users/2883841', 'pm_score': 2, 'selected': False, 'text': '<p>Just faced a similar problem - "Search and replace text within files", but with the exception that for both filenames and search/repalce I need to use regex. Because I\'m not familiar with Powershell and want to save my searches for later use I need something more "user friendly" (preferable if it has GUI). </p>\n\n<p>So, while Googling :) I found a great tool - <a href="http://findandreplace.sourceforge.net/" rel="nofollow">FAR (Find And Replace)</a> (not FART). </p>\n\n<p>That little program has nice GUI and support regex for searching in filenames and within files. Only disadventage is that if you want to save your settings you have to run the program as an administrator (at least on Win7).</p>\n'}, {'answer_id': 33149373, 'author': 'npocmaka', 'author_id': 388389, 'author_profile': 'https://Stackoverflow.com/users/388389', 'pm_score': 4, 'selected': False, 'text': '<p>With the  <a href="https://github.com/npocmaka/batch.scripts/blob/master/hybrids/jscript/replacer.bat">replacer.bat</a></p>\n\n<p>1) With <code>e?</code> option that will evaluate special character sequences like <code>\\n\\r</code> and unicode sequences. In this case will replace quoted <code>"Foo"</code> and <code>"Bar"</code>:</p>\n\n<pre><code>call replacer.bat "e?C:\\content.txt" "\\u0022Foo\\u0022" "\\u0022Bar\\u0022"\n</code></pre>\n\n<p>2) Straightforward replacing where the <code>Foo</code> and <code>Bar</code> are not quoted.</p>\n\n<pre><code>call replacer.bat "C:\\content.txt" "Foo" "Bar"\n</code></pre>\n'}, {'answer_id': 33762001, 'author': 'Jens A. Koch', 'author_id': 1163786, 'author_profile': 'https://Stackoverflow.com/users/1163786', 'pm_score': 4, 'selected': False, 'text': '<p>When you work with <a href="https://git-for-windows.github.io/" rel="noreferrer"><strong>Git on Windows</strong></a> then simply fire up <strong><code>git-bash</code></strong> \nand use <strong><code>sed</code></strong>. Or, when using Windows 10, start "Bash on Ubuntu on Windows" (from the Linux subsystem) and use <strong><code>sed</code></strong>.</p>\n\n<p>Its a stream editor, but can edit files directly by using the following command:</p>\n\n<pre><code>sed -i -e \'s/foo/bar/g\' filename\n</code></pre>\n\n<ul>\n<li><code>-i</code> option is used to edit in place on filename.</li>\n<li><code>-e</code> option indicates a command to run.\n\n<ul>\n<li><code>s</code> is used to replace the found expression "foo" with "bar" and <code>g</code> is used to replace any found matches.</li>\n</ul></li>\n</ul>\n\n<hr>\n\n<p>Note by ereOn: </p>\n\n<p>If you want to replace a string in versioned files only of a Git repository, you may want to use: </p>\n\n<p><code>git ls-files &lt;eventual subfolders &amp; filters&gt; | xargs sed -i -e \'s/foo/bar/g\'</code> </p>\n\n<p>which works wonders.</p>\n'}, {'answer_id': 44577233, 'author': 'Whome', 'author_id': 185565, 'author_profile': 'https://Stackoverflow.com/users/185565', 'pm_score': 2, 'selected': False, 'text': '<p>@Rachel gave an excellent answer but here is a variation of it to read content to a powershell <code>$data</code> variable. You may then easily manipulate content multiple times before writing to a output file. Also see how multi-line values are given in a .bat batch files.</p>\n\n<pre><code>@REM ASCII=7bit ascii(no bom), UTF8=with bom marker\nset cmd=^\n  $old = \'\\$Param1\\$\'; ^\n  $new = \'Value1\'; ^\n  [string[]]$data = Get-Content \'datafile.txt\'; ^\n  $data = $data -replace $old, $new; ^\n  out-file -InputObject $data -encoding UTF8 -filepath \'datafile.txt\';\npowershell -NoLogo -Noninteractive -InputFormat none -Command "%cmd%"\n</code></pre>\n'}, {'answer_id': 49675231, 'author': 'George Birbilis', 'author_id': 903783, 'author_profile': 'https://Stackoverflow.com/users/903783', 'pm_score': 0, 'selected': False, 'text': '<p>Can also see the Replace and ReplaceFilter tools at <a href="https://zoomicon.github.io/tranXform/" rel="nofollow noreferrer">https://zoomicon.github.io/tranXform/</a> (source included). The 2nd one is a filter. </p>\n\n<p>The tool that replaces strings in files is in VBScript (needs Windows Script Host [WSH] to run in old Windows versions)</p>\n\n<p>The filter is probably not working with Unicode unless you recompile with latest Delphi (or with FreePascal/Lazarus)</p>\n'}, {'answer_id': 49868359, 'author': 'Wagner Pereira', 'author_id': 3954704, 'author_profile': 'https://Stackoverflow.com/users/3954704', 'pm_score': 2, 'selected': False, 'text': '<p>Use powershell in .bat - for Windows 7+</p>\n\n<p>encoding utf8 is optional, good for web sites</p>\n\n<pre><code>@echo off\nset ffile=\'myfile.txt\'\nset fold=\'FOO\'\nset fnew=\'BAR\'\npowershell -Command "(gc %ffile%) -replace %fold%, %fnew% | Out-File %ffile% -encoding utf8"\n</code></pre>\n'}, {'answer_id': 55664924, 'author': 'eQ19', 'author_id': 4058484, 'author_profile': 'https://Stackoverflow.com/users/4058484', 'pm_score': 3, 'selected': False, 'text': '<p>I\'m prefer to use <code>sed</code> from <a href="http://unxutils.sourceforge.net/" rel="noreferrer">GNU utilities for Win32</a>, the followings need to be noted</p>\n\n<blockquote>\n  <ul>\n  <li>single quote <code>\'\'</code> won\'t work in windows, use <code>""</code> instead</li>\n  <li><strong><code>sed -i</code></strong> won\'t work in windows, it will need file <strong>swapping</strong></li>\n  </ul>\n</blockquote>\n\n<p>So the working code of <code>sed</code> to find and replace text in a file in windows is as below</p>\n\n<pre><code>sed -e "s/foo/bar/g" test.txt &gt; tmp.txt &amp;&amp; mv tmp.txt test.txt\n</code></pre>\n'}, {'answer_id': 68204080, 'author': 'Shivam Tyagi', 'author_id': 8071857, 'author_profile': 'https://Stackoverflow.com/users/8071857', 'pm_score': 0, 'selected': False, 'text': '<p>Powershell Command -</p>\n<p>Getting content of the file and replacing it with some other text and then storing into another file</p>\n<p><strong>Command -1</strong>\n(Get-Content filename.xml)| ForEach-Object { $_.replace(&quot;some_text&quot;,&quot;replace_text&quot;).replace(&quot;some_other_text&quot;,&quot;replace_text&quot;) } | Set-Content filename2.xml</p>\n<p>Copying another file into the original one file</p>\n<p><strong>Command2</strong></p>\n<p>Copy-Item -Path filename2.xml -Destination filename.xml -PassThru</p>\n<p>removing another one file</p>\n<p><strong>Command 3</strong></p>\n<p>Remove-Item filename2.xml</p>\n'}, {'answer_id': 69695302, 'author': 'Georgie', 'author_id': 2344075, 'author_profile': 'https://Stackoverflow.com/users/2344075', 'pm_score': 2, 'selected': False, 'text': "<p>For me, to be sure to not change the encoding (from UTF-8), keeping accents... the only way was to mention the default encoding before and after :</p>\n<pre><code>powershell -Command &quot;(gc 'My file.sql' -encoding &quot;Default&quot;) -replace 'String 1', 'String 2' | Out-File -encoding &quot;Default&quot; 'My file.sql'&quot;\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/60034', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4872/']