529

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?

Ray
  • 169,974
  • 95
  • 213
  • 200
  • findstr: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/findstr.mspx find: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/find.mspx – n611x007 Aug 28 '14 at 16:12
  • use this : `echo(%text:%search%=%replace%%)` –  Aug 06 '19 at 10:07

27 Answers27

352

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.

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:

powershell -Command "(gc myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt"

To explain it:

  • powershell starts up powershell.exe, which is included in Windows 7
  • -Command "... " is a command line arg for powershell.exe containing the command to run
  • (gc myFile.txt) reads the content of myFile.txt (gc is short for the Get-Content command)
  • -replace 'foo', 'bar' simply runs the replace command to replace foo with bar
  • | Out-File myFile.txt pipes the output to the file myFile.txt
  • -encoding ASCII prevents transcribing the output file to unicode, as the comments point out

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 C:\WINDOWS\system32\WindowsPowerShell\v1.0

Update
Apparently modern windows systems have PowerShell built in allowing you to access this directly using

(Get-Content myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt
Rachel
  • 122,023
  • 59
  • 287
  • 465
  • 74
    Beware, this command may also transcode the file to Unicode encoding. You can manually specify the encoding by adding `-encoding ASCII` or `UTF8` or whatever is needed. Also beware, if you target UTF8, it may introduce a Byte Order Mark at the beginning of the file that did not appear in the original. – Wyck Mar 28 '14 at 17:23
  • 80
    @Wyck It took me a while to figure out where to put `-encoding ASCII`. For anyone needing it in the future, it would be `Out-File -encoding ASCII myFile.txt` – rwilson04 May 07 '14 at 20:38
  • 16
    The only thing I had to change was to use `Set-Content` instead of `Out-File`. – kurtzmarc Dec 29 '14 at 20:08
  • 8
    This works, but the performance is terrible on even a short list of files. – jsuddsjr Jun 08 '15 at 20:55
  • 24
    Beware that the replace token ('foo' in this case) is treated as a regular expression. If you have any special characters there ( I had [ ] ), you need to prepend them with a \ (backslash). – J W Mar 03 '16 at 16:11
  • 4
    To escape special characters, one can also use 'foo-bar' (apostrophes) in the regular expression. – pepan Mar 10 '16 at 14:04
  • On a single file with close to 40.000 lines, performance was really good. Thanks for a great answer! – carlossierra Mar 15 '17 at 20:18
  • How would you replace case-sensitively? I tried -creplace but that doesn't seem to work. – Cthutu Aug 16 '18 at 14:20
  • 1
    @cthutu `-ireplace` is the case insensitive `-replace` – WEBjuju Jan 28 '19 at 21:32
  • It should be noted that by default the PowerShell execution is restricted, so you may not be able to run that by default on a system. You can easily disable this with another parameter for PowerShell however, see https://stackoverflow.com/a/9167524/5008962 – rugk Feb 08 '19 at 09:33
  • 2
    Another issue with this vs a similar statement in the `sed` utility, is that the way it's written, it will read the entire source file into memory before doing a replacement. If you're using it on large files (e.g. MySQLDump) it will max out your system resources very quickly. Using something similar like, `filter replace-strs { $_ -replace 'foo', 'bar' } if (test-path outFile.txt) { Clear-Content outFile.txt } Get-Content myFile.txt | replace-strs | Add-Content outFile.txt` should work line-by-line. – Lovethenakedgun May 14 '19 at 04:32
  • Tip: If your filenames have spaces within them, you need to surround them in single quotes. – Simon East Sep 24 '19 at 08:57
  • 4
    **Important:** Unless you really want to use regular expressions, you should disable `foo` and `bar` from being treated as regex (which often causes issues). To do this you modify the script slightly from `(gc 'myFile.txt') -replace 'foo', 'bar'` to `(gc 'myFile.txt').replace('foo', 'bar')` – Simon East Sep 24 '19 at 10:50
  • This worked for me but suddenly stopped after I changed the filenames, without any error messages. The files are saved, but the strings are not replaced. I'm going crazy here. – Adam Jagosz Feb 19 '20 at 18:31
  • 2
    To find/replace special characters (like newline (`\n`) or tab (`\t`)), use double quotes and a backtick. For example, to replace spaces with tabs: ``-replace ' ', "`t"``. – srk Jun 30 '20 at 20:29
  • I used encoding UTF8 instead of encoding ASCII for my UTF-8 text file but it messed the file – Joe Jobs Dec 30 '20 at 22:13
184

If you are on Windows version that supports .Net 2.0, I would replace your shell. PowerShell 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.

(Get-Content test.txt) | ForEach-Object { $_ -replace "foo", "bar" } | Set-Content test2.txt
Michael Haren
  • 97,268
  • 39
  • 159
  • 200
Mike Schall
  • 5,621
  • 3
  • 34
  • 46
  • 2
    I second the vote for PowerShell. It gives you just an extremely capable shell. – Steven Murawski Sep 13 '08 at 00:17
  • 11
    I can see PowerShell is capable of archieving this. But how can I make this run from a batch file (example: myProc.bat)? – Pablo Venturino Mar 03 '10 at 12:43
  • 3
    @Pablo, use powershell.exe and wrap ps command into single parameter – lubos hasko Mar 05 '10 at 08:13
  • 56
    -1.. Sure the answer was accepted, but it's not answer to the specified question. – baash05 May 02 '12 at 01:29
  • I posted another variation of Mike's answer where the data is piped into Powershell (see below). – Simon East May 07 '12 at 23:29
  • 29
    This will fail with a file in use error if you save to the same file. You need to change the powershell command to: (Get-Content test.txt) | ForEach-Object { $_ -replace "foo", "bar" } | Set-Content test.txt – BigMomma Aug 29 '12 at 12:29
  • I'm trying to put this in a function but it doesn't work like that, neither does it show an error message. It just writes the same content. Could somebody please tell me what's wrong? `function Replace { (Get-Content $args[0]) | ForEach-Object { $_ -replace "$($args[1])", "$($args[2])" } | Set-Content $args[0] } Replace test.txt foo bar` – lapis May 20 '13 at 22:18
  • @Psycho, It looks like you have an extra $() round your replacements... does the following work? function Replace { (Get-Content $args[0]) | ForEach-Object { $_ -replace "$args[1]", "$args[2]" } | Set-Content $args[0] } – Mike Schall May 21 '13 at 16:00
  • @Mike, that's the syntax (odd-looking, I agree) for referencing array elements in replacements, without it it prints the whole array and then the string "[1]" (or "[2]" respectively). – lapis May 21 '13 at 17:03
  • In PowerShell v3 there is -Raw parameter for Get-Content which makes processing large files significantly faster (in my case 200 times faster). It reads the whole file as a string not as an array of lines. – Pavel Hodek Jul 23 '13 at 18:44
  • Technically does not answer the original question, Powershell requires elevated privileges and may not be appropriate in all situations – gareththegeek Jul 30 '13 at 14:43
  • 2
    @gareththegeek You have a false assumption. Powershell does not require elevated privileges. I'm saying this so that future readers know this. – Janis Veinbergs Oct 24 '13 at 05:49
  • What if I want to replace the content in the same file ( and not save a new file) ? – Royi Namir Nov 11 '13 at 11:13
  • @royinamir: I would guess that the following untested code would work: Get-Content test.txt | ForEach-Object { $_ -replace "foo", "bar" } | Set-Content test.txt – Mike Schall Nov 13 '13 at 02:29
  • @MikeSchall No. file in use. – Royi Namir Nov 13 '13 at 05:53
  • 2
    @royinamir: Looks like putting parentheses around the get content might solve the problem? Sorry, no pc around to test on right now... http://stackoverflow.com/questions/10239702/powershell-set-content-having-issues-with-file-already-in-use – Mike Schall Nov 14 '13 at 06:26
  • 8
    See the answer from @Rachel: `powershell -Command "(gc myFile.txt) -replace 'foo', 'bar' | sc myFile.txt"` – Nigel Touch Mar 26 '15 at 10:58
  • This sounds like a good idea, but can be big waste of time (I would NOT recommend this for the inexperienced). If you skipped BAT/CMD FOR/IF because you need regex, then your match symbols could hit issues in any of the 4 layers of command interpolation: BAT, PowerShell.exe argument parsing, PowerShell script (inside parens), PowerShell command (outside parens -- yes, it's different). Warning: Out-File will change encoding to UTF-16. Try anything once, but if it doesn't work the first time don't even try to figure it out. Either embrace POSH (ditch CMD) or get a tool like `sed`. – yzorg May 21 '16 at 17:13
  • 2
    How would this be done for all files in dir of a given extension? – CaptainMarvel Sep 14 '16 at 22:04
  • Powershell is more powerful, but boy does it suck anyway. I wish they'd done something more like 4DOS / Take Command – GeeWhizBang Dec 05 '17 at 18:26
170

Just used FART ("F ind A nd R eplace T ext" command line utility):
excellent little freeware for text replacement within a large set of files.

The setup files are on SourceForge.

Usage example:

fart.exe -p -r -c -- C:\tools\perl-5.8.9\* @@APP_DIR@@ C:\tools

will preview the replacements to do recursively in the files of this Perl distribution.

Only problem: the FART website icon isn't exactly tasteful, refined or elegant ;)


Update 2017 (7 years later) jagb points out in the comments to the 2011 article "FARTing the Easy Way – Find And Replace Text" from Mikail Tunç


As noted by Joe Jobs in the comments (Dec. 2020), if you want to replace &A for instance, you would need to use quotes in order to make sure & is not interpreted by the shell:

fart in.txt "&A" "B" 
VonC
  • 1,042,979
  • 435
  • 3,649
  • 4,283
  • 20
    The cool thing is it's one single exe. No dependencies. No small prints. Super easy to deploy. – Serge Wautier Mar 02 '11 at 17:24
  • 1
    Thanks for the fart recommendation. Seems to work well, although I wish it supported regex. – Gary Kephart Jul 09 '11 at 16:57
  • 2
    Very lightweight and easy to use, but I was hoping it would print out the exact places that replacements took place. Not being able to see that gave me a sense of insecurity. – William Niu Sep 06 '11 at 07:39
  • 4
    Thanks, it's perfect, should be part of the standard dos tools and worked a charm. The -p option however doesn't show you how many changes it 'would' make and always reports 0 which threw me for a few mins – sradforth Jan 10 '12 at 14:53
  • Very useful! (it's also very fast even on big files... like replacing all space with tab on 4Mb firewall log file (doing Excel analysis...)) – Max Oct 09 '12 at 15:51
  • 4
    I understand this is a very old question but I found more information and hope it will be helpful to Stack Overflow users. Just another link for FART where product is well explained: [FART explaned @emtunc.org](https://emtunc.org/blog/03/2011/farting-the-easy-way-find-and-replace-text/) and another page can be found here: [FART](http://fart-it.sourceforge.net/) **Please be careful with the replacement of `/` and `'` as this is not working for all of us**, for me it worked in some cases but it didn't work on some files and I don't know why.. I used this to replace text with other text and a `/` – jagb Mar 10 '17 at 01:22
  • 4
    @jagb Thank you. I have included your link in the answer for more visibility. – VonC Mar 10 '17 at 05:35
  • I want to replace "&A" with "B" so I used "fart IN.txt &A B" and it doesn't work and I get this error: 'A' is not recognized as an internal or external command – Joe Jobs Dec 30 '20 at 21:49
  • @JoeJobs Strange: can you illustrate that issue in a separate question? Do add details on the exact OS version and shell version (CMD, git for Windows bash, cygwin...) used. – VonC Dec 30 '20 at 22:48
  • I am using FART 1.99 in Windows 10 - CMD. It looks like it has a problem with the & character – Joe Jobs Dec 31 '20 at 01:18
  • @JoeJobs Did you try adding quotes? As in `fart in.txt "&A" "B"` – VonC Dec 31 '20 at 01:22
  • No because I thought it will search for quotes. Now I tried with quotes and it works. I think you should make that clear in the answer and also to mention how to search for quotes. This tool is really useful – Joe Jobs Dec 31 '20 at 02:10
  • 1
    @JoeJobs Sure: I have included your comment and this example in the answer for more visibility. – VonC Dec 31 '20 at 02:31
  • In fact my task was replacing "&" with "&" - might be better as an example because it is a common replacement. Also I think it is really worth to show that FART can replace string containing spaces, by using quotes. By looking at the first usage example, I got the feeling that it can't search for spaces – Joe Jobs Dec 31 '20 at 04:02
  • @JoeJobs I agree. Again, feel free to edit the answer to improve those examples. – VonC Dec 31 '20 at 04:05
134

Replace - Replace a substring using string substitution Description: 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.

set str=teh cat in teh hat
echo.%str%
set str=%str:teh=the%
echo.%str%

Script Output:

teh cat in teh hat
the cat in the hat

ref: http://www.dostips.com/DtTipsStringManipulation.php#Snippets.Replace

RB.
  • 33,692
  • 12
  • 79
  • 121
Bill Richardson
  • 1,413
  • 1
  • 9
  • 2
  • 31
    How is the sed suggestion better? This seems to be the most simple answer of them all and requires installing nothing. – DonBecker Jan 20 '12 at 20:18
  • 5
    Can any sort of pattern matching be done here? Wildcards, Regex etc? – Keyo Apr 19 '12 at 21:51
  • 28
    "How is the sed suggestion better?" - sed and similar utilities operate on files; this snippet omits the important step of reading lines from the input file and writing to the output file, while ensuring that any special characters in the file are handled correctly. – Joe Jun 13 '13 at 11:25
  • @Joe Wrong. You can pipe any output to sed, files are not necessary. – Asad Saeeduddin Feb 15 '14 at 05:32
  • 7
    @Asad, yes that's true, the OP was asking about files, but in fact it works with streams which don't have to be files. But my point here is that this answer is flawed, since it omits reading/writing from a stream and handling any special characters. – Joe Feb 15 '14 at 08:57
  • 4
    @Bill how to use variable as a replacing text? ie. I have value in a variable and a string which has some delimter. set str=%str:"##"=%varValue%% doesn't work. Any workarounds? – MalTec Apr 04 '14 at 10:32
  • @MalTec, I am just trying that, to place some text with `%s`, but I couldn't do it so far. I could kind of escape it in an echo command with `^` but not in a set command. – Andrew May 10 '15 at 03:07
  • Thank you for actually answering what the OP asked for - something that's simple and in-built to the CMD shell. –  Jun 13 '15 at 22:10
  • 2
    Ok, this replaces text in a environment variable, but how to use it to replace the content of a file? – neves Mar 16 '16 at 20:32
  • In case you want to use this in a loop one would need to use EnableDelayedExpansion like described at https://stackoverflow.com/questions/8281242/how-to-apply-substring-command-to-double-percent-variable-in-xp-cmd-scripts?rq=1 – Florian Straub Nov 02 '18 at 15:02
59

Create file replace.vbs:

Const ForReading = 1    
Const ForWriting = 2

strFileName = 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.Write strNewText  'WriteLine adds extra CR/LF
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:\Scripts\Text.txt" "Jim " "James "

JamesQMurphy
  • 3,732
  • 1
  • 33
  • 37
user459118
  • 1,044
  • 9
  • 6
  • this is neat, does it allow the use of RegEx? – user280109 Jan 24 '14 at 21:35
  • 3
    @user280109 Yes, VBScript supports `RegExp`. You can use this to replace using a regular expression: `With (New RegExp): strNewText = .Replace(strText, strOldText, strNewText): End With`. You can get the text of the first 9 capturing groups using `$1`, `$2` ... `$9`. – Toothbrush Jun 17 '14 at 10:30
  • 2
    VBScript is often overlooked (and hated on), but is available on all Windows platforms, is very readable and actually has very powerful capabilities +1 – zelanix Sep 05 '16 at 16:31
  • 1
    @user280109 You just given the command, What i need. But i want to replace (case-insensitive) Can you provide the command for that? – Ajmal Praveen Sep 26 '17 at 15:22
  • Thank you, This script was great, I love your prefix (str and obj word), I do the same, It's old but gold, It's make code more readable. – Ali.P May 11 '21 at 12:17
51

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.

dbenham
  • 119,153
  • 25
  • 226
  • 353
  • Great stuff! I love this b/c of the simplicity and the way you can adapt it to whatever script, hence writing JS code than crappy batch. – Adaptabi Jun 23 '13 at 21:29
  • Edit - Added the A option to only print lines that have been modified. Also enhanced the X option to support `\q` to represent `"`, and Search literals now support all the extended escape sequences when L and X options are combined. – dbenham Jun 30 '13 at 02:25
  • @dbenham - +1. This is a slick approach, it will come in handy for several other tasks as well. Thanks for posting it. – b w Sep 26 '13 at 17:44
  • EDIT - I modified behavior of \xnn when X option is used so that the code represents the extended ASCII byte code. Also added a /V version option. – dbenham Oct 02 '13 at 18:40
  • EDIT - updated code to version 3.3: Option A can now be combined with M if S is also used. Also added new help options /?REGEX and /?REPLACE to automatically open relevant MicroSoft documentation in your browser. – dbenham Apr 05 '14 at 17:03
  • EDIT - updated code to version 4.0. Option N added to enable reading binary files containing NULL bytes. This is a work-around to a bug with `WScript.StdIn.ReadAll()`. See http://www.dostips.com/forum/viewtopic.php?p=36033#p36033 – dbenham Jul 28 '14 at 11:23
  • EDIT - updated code to v4.1. Option N removed. M option now always works properly with binary files. Also improved performance with binary files. – dbenham Jul 31 '14 at 00:30
  • EDIT - updated code to v5.0 - Refined and documented return codes. You can now tell whether REPL.BAT makes a change to the data or not. – dbenham Oct 28 '14 at 21:37
  • EDIT - updated code to v6.0 - Added J option to specify replacement value as a JScript expression. See http://www.dostips.com/forum/viewtopic.php?p=37855#p37855 for details and examples. – dbenham Nov 07 '14 at 20:07
  • EDIT - updated code to v6.2 - Bug fix - $ should not be escaped in Replace if J option used. Also corrected description of A option. – dbenham Nov 11 '14 at 18:13
  • 9
    @dbenham This is a gem. Why don't you put it up on GitHub or as a Gist? Would make versioning, follow-ups, releases/distribution, fixes and more easier. If you need help with that, let me know. – Atif Aziz Jul 16 '15 at 08:20
  • @AtifAziz Agreed! dbenham, any thoughts? I personally find full repos on github easier to work with than Gists, so that would be my vote. – cxw Feb 26 '17 at 15:59
  • @Pogrindis - I hope you are using the newer JREPL.BAT instead of the outdated (superseded) REPL.BAT – dbenham Jun 30 '17 at 13:44
  • Fixed the link to JREPL.BAT – dbenham Jun 30 '17 at 14:03
51

BatchSubstitute.bat on dostips.com is an example of search and replace using a pure batch file.

It uses a combination of FOR, FIND and CALL SET.

Lines containing characters among "&<>]|^ may be treated incorrectly.


Community
  • 1
  • 1
morechilli
  • 9,326
  • 7
  • 30
  • 53
  • 9
    I have to question the usefulness of a code snippet site whose [terms of use](http://www.dostips.com/DtGeneTermsOfUse.php) prohibit copying any of the code (“You may not distribute any information provided under the domain dostips.com in any form without express written permission of the domain owner.”). – Gilles 'SO- stop being evil' Apr 11 '12 at 08:34
  • 1
    I agree their terms are confusing, they also say "The information provided under the domain dostips.com is hopefully useful" so my assumption is that they are happy for people to copy the code to solve a problem. I'm not sure I have ever read any terms and conditions and been happy... – morechilli Apr 16 '12 at 09:58
  • 5
    This is great. I love answers that don't involve downloading something else to do it. – Ruairi O'Brien Jun 11 '12 at 09:42
  • I also like solutions that don't involve external utilities, unfortunately, I keep getting "find: invalid predicate `'" when I try to run this batch. Don't really have the time to debug it right now. – Jahmic Jul 27 '13 at 08:09
  • 2
    The "find: invalid predicate `'" error was due to an external 'find' utility on my system. Once removed, this worked fine. – Jahmic Jul 27 '13 at 08:40
38

Use FNR

Use the fnr utility. It's got some advantages over fart:

  • Regular expressions
  • Optional GUI. Has a "Generate command line button" to create command line text to put in batch file.
  • Multi-line patterns: The GUI allows you to easily work with multi-line patterns. In FART you'd have to manually escape line breaks.
  • Allows you to select text file encoding. Also has an auto detect option.

Download FNR here: http://findandreplace.io/?z=codeplex

Usage example: fnr --cl --dir "<Directory Path>" --fileMask "hibernate.*" --useRegEx --find "find_str_expression" --replace "replace_string"

Community
  • 1
  • 1
Aman
  • 836
  • 10
  • 16
27

I don't think there's a way to do it with any built-in commands. I would suggest you download something like Gnuwin32 or UnxUtils and use the sed command (or download only sed):

sed -c s/FOO/BAR/g filename
Pat
  • 15,269
  • 13
  • 86
  • 106
Ferruccio
  • 93,779
  • 37
  • 217
  • 294
  • 2
    Use cygwin (http://www.cygwin.com). It's the next best thing to actually installing linux. – Andrew Johnson Sep 12 '08 at 22:12
  • It's better if one can provide a solution that doesn't rely on installing cygwin. POSIX string manipulation is a no-brainer - doing this on Windows is a little more obscure. – Rex Jul 17 '12 at 10:10
  • 4
    Gnuwin32 and UnxUtils are stand-alone binaries built for Windows. They are not dependent on cygwin. – Ferruccio Jul 17 '12 at 11:47
  • 1
    cygwin: `sed -i -b -e 's/FOO/BAR/g' \`find . -name *.txt\`` -i -- edit file inplace; -b -- do not process CR+LF - without this option CR+LF would be converted to LF – Alexey Vishentsev Jul 25 '13 at 07:01
  • @AndrewJohnson Opinion and information are two different things. – Preza8 Jan 30 '20 at 17:15
25

I know I am late to the party..

Personally, I like the solution at: - http://www.dostips.com/DtTipsStringManipulation.php#Snippets.Replace

We also, use the Dedupe Function extensively to help us deliver approximately 500 e-mails daily via SMTP from: - https://groups.google.com/forum/#!topic/alt.msdos.batch.nt/sj8IUhMOq6o

and these both work natively with no extra tools or utilities needed.

REPLACER:

DEL New.txt
setLocal EnableDelayedExpansion
For /f "tokens=* delims= " %%a in (OLD.txt) do (
Set str=%%a
set str=!str:FOO=BAR!
echo !str!>>New.txt
)
ENDLOCAL

DEDUPLICATOR (note the use of -9 for an ABA number):

REM DE-DUPLICATE THE Mapping.txt FILE
REM THE DE-DUPLICATED FILE IS STORED AS new.txt

set MapFile=Mapping.txt
set ReplaceFile=New.txt

del %ReplaceFile%
::DelDupeText.bat
rem https://groups.google.com/forum/#!topic/alt.msdos.batch.nt/sj8IUhMOq6o
setLocal EnableDelayedExpansion
for /f "tokens=1,2 delims=," %%a in (%MapFile%) do (
set str=%%a
rem Ref: http://www.dostips.com/DtTipsStringManipulation.php#Snippets.RightString
set str=!str:~-9!
set str2=%%a
set str3=%%a,%%b

find /i ^"!str!^" %MapFile%
find /i ^"!str!^" %ReplaceFile%
if errorlevel 1 echo !str3!>>%ReplaceFile%
)
ENDLOCAL

Thanks!

Leptonator
  • 3,033
  • 1
  • 33
  • 47
  • the batch script does nothing but a mere file-copy - also : why are you thanking yourself? – specializt Feb 11 '16 at 07:45
  • The original request was to replace "FOO" with "BAR" in a text file using a batch script and with preferably built-in functions. If anything I was thanking the Google Groups post I had found which works fantastic and we still use it to this day. Also, see posts and responses like these as being helpful for users coming down the road as well. I fail to see your comment about file copy.. Sure, it takes the content of one file and echo's the result into another file, but based on the data, it does trim and parse off the needed information. I would recommend giving it a try first. ;) – Leptonator Feb 11 '16 at 18:48
  • its basically a file-copy tool which replaces two static strings - you could've at least placed two variables in there so people who **want** to try it wont need to understand the syntax in order to actually be able to use it -- also : assumptions over the internet are almost always completely wrong. Remember that. – specializt Feb 12 '16 at 12:42
  • OK.. So, do you recommend my re-writing the code? And, if so, do you have some suggestions? I guess where I am at with this right now, is that it works. I see your point, but yet while it is using static variables, it does "deduplicate" which overcomes the major hurdle. While there are tools that accomplish the needs of this, using the native CMD addresses the need. I know that the Internet is not always trustworthy (hence the comment about being the "bathroom wall" and people will write most anything they want) - you have to test and verify and re-verify and be careful what we publish. – Leptonator Feb 12 '16 at 16:06
  • who is "we" and what is "static variable" supposed to mean - other than static object variables / members? – specializt Feb 12 '16 at 16:09
  • 6
    @specializt - Please... I am not here to debate semantics. If you like, can we take this offline into the chat room. – Leptonator Feb 12 '16 at 16:19
  • 5
    In my opinion, *this* is the answer to the original question. I will be using this tip to configure initialization files for a service during setup, and I would not want to enable PowerShell, or allow the scripting engine to run on my servers. So often answers to questions related to windows, start with "install this gizmo from there" as there is still a "PC" attitude around. – mico Sep 12 '18 at 11:14
15

When you work with Git on Windows then simply fire up git-bash and use sed. Or, when using Windows 10, start "Bash on Ubuntu on Windows" (from the Linux subsystem) and use sed.

Its a stream editor, but can edit files directly by using the following command:

sed -i -e 's/foo/bar/g' filename
  • -i option is used to edit in place on filename.
  • -e option indicates a command to run.
    • s is used to replace the found expression "foo" with "bar" and g is used to replace any found matches.

Note by ereOn:

If you want to replace a string in versioned files only of a Git repository, you may want to use:

git ls-files <eventual subfolders & filters> | xargs sed -i -e 's/foo/bar/g'

which works wonders.

Jens A. Koch
  • 34,456
  • 12
  • 100
  • 117
  • 1
    Note that if you are indeed doing that rename in a git repository and only want to replace in versionned files, you may want to do: `git ls-files | xargs sed -i -e 's/foo/bar/g'` which works wonders. – ereOn Mar 16 '16 at 20:58
13

I played around with some of the existing answers here and prefer my improved solution...

type test.txt | powershell -Command "$input | ForEach-Object { $_ -replace \"foo\", \"bar\" }"

or if you want to save the output again to a file...

type test.txt | powershell -Command "$input | ForEach-Object { $_ -replace \"foo\", \"bar\" }" > outputFile.txt

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... :-(

Simon East
  • 46,575
  • 14
  • 130
  • 124
  • 3
    This is a good solution. Unfortunately, using `type` means all lines greater than 80 characters get wrapped. What a pain. – sirdank Feb 16 '15 at 20:05
12

I have used perl, and that works marvelously.

perl -pi.orig -e "s/<textToReplace>/<textToReplaceWith>/g;" <fileName>

.orig is the extension it would append to the original file

For a number of files matching such as *.html

for %x in (<filePattern>) do perl -pi.orig -e "s/<textToReplace>/<textToReplaceWith>/g;" %x
CoolBeans
  • 20,016
  • 10
  • 81
  • 98
Faisal
  • 121
  • 1
  • 2
  • This is the simplest solution +1, when converting from sh to bat, just replace `sed` with `perl -pi.backup -e` and appreciate it :) – Yann39 May 27 '16 at 11:50
11

With the replacer.bat

1) With e? option that will evaluate special character sequences like \n\r and unicode sequences. In this case will replace quoted "Foo" and "Bar":

call replacer.bat "e?C:\content.txt" "\u0022Foo\u0022" "\u0022Bar\u0022"

2) Straightforward replacing where the Foo and Bar are not quoted.

call replacer.bat "C:\content.txt" "Foo" "Bar"
npocmaka
  • 51,748
  • 17
  • 123
  • 166
  • it's not working for me. How do you run this? I am receiving error 'replace_in_config.bat' is not recognized as an internal or external command, operable program or batch file. – FrenkyB Aug 08 '19 at 06:35
  • @FrenkyB - it needs to be in the same directory where you calling it or in the path - https://ss64.com/nt/path.html – npocmaka Aug 08 '19 at 08:25
  • I've had all three files in the same directory. – FrenkyB Aug 09 '19 at 09:11
9

Here's a solution that I found worked on Win XP. In my running batch file, I included the following:

set value=new_value

:: Setup initial configuration
:: I use && as the delimiter in the file because it should not exist, thereby giving me the whole line
::
echo --> Setting configuration and properties.
for /f "tokens=* delims=&&" %%a in (config\config.txt) do ( 
  call replace.bat "%%a" _KEY_ %value% config\temp.txt 
)
del config\config.txt
rename config\temp.txt config.txt

The replace.bat file is as below. I did not find a way to include that function within the same batch file, because the %%a variable always seems to give the last value in the for loop.

replace.bat:

@echo off

:: This ensures the parameters are resolved prior to the internal variable
::
SetLocal EnableDelayedExpansion

:: Replaces Key Variables
::
:: Parameters:
:: %1  = Line to search for replacement
:: %2  = Key to replace
:: %3  = Value to replace key with
:: %4  = File in which to write the replacement
::

:: Read in line without the surrounding double quotes (use ~)
::
set line=%~1

:: Write line to specified file, replacing key (%2) with value (%3)
::
echo !line:%2=%3! >> %4

:: Restore delayed expansion
::
EndLocal
Gilles 'SO- stop being evil'
  • 92,660
  • 35
  • 189
  • 229
Chad
  • 91
  • 1
  • 2
7

Take a look at Is there any sed like utility for cmd.exe which asked for a sed equivalent under Windows, should apply to this question as well. Executive summary:

  • It can be done in batch file, but it's not pretty
  • 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
  • Can be done with VBScript or similar if you need something able to run on a Windows box without modification etc.
Community
  • 1
  • 1
Jay
  • 39,240
  • 14
  • 62
  • 82
5

Two batch files that supply search and replace functions have been written by Stack Overflow members dbenham and aacini using native built-in jscript in Windows.

They are both robust and very swift with large files compared to plain batch scripting, and also simpler to use for basic replacing of text. They both have Windows regular expression pattern matching.

  1. Thissed-like helper batch file is called repl.bat (by dbenham).

    Example using the L literal switch:

    echo This is FOO here|repl "FOO" "BAR" L
    echo and with a file:
    type "file.txt" |repl "FOO" "BAR" L >"newfile.txt"
    
  2. This grep-like helper batch file is called findrepl.bat (by aacini).

    Example which has regular expressions active:

    echo This is FOO here|findrepl "FOO" "BAR" 
    echo and with a file:
    type "file.txt" |findrepl "FOO" "BAR" >"newfile.txt"
    

Both become powerful system-wide utilities when placed in a folder that is on the path, or can be used in the same folder with a batch file, or from the cmd prompt.

They both have case-insensitive switches and also many other functions.

Usman Maqbool
  • 3,073
  • 10
  • 28
  • 41
foxidrive
  • 37,659
  • 8
  • 47
  • 67
4

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.

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 here. 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.

Peter Schuetze
  • 15,675
  • 3
  • 39
  • 57
4

Power shell command works like a charm

(
test.txt | ForEach-Object { $_ -replace "foo", "bar" } | Set-Content test2.txt
)
Cody Gray
  • 222,280
  • 47
  • 466
  • 543
4

I'm prefer to use sed from GNU utilities for Win32, the followings need to be noted

  • single quote '' won't work in windows, use "" instead
  • sed -i won't work in windows, it will need file swapping

So the working code of sed to find and replace text in a file in windows is as below

sed -e "s/foo/bar/g" test.txt > tmp.txt && mv tmp.txt test.txt
Chetabahana
  • 7,806
  • 2
  • 50
  • 70
  • 3
    Before Windows users immediately do file swapping: newer versions of sed support in-place editing with `-i`! If your sed version does, then check the command from this answer: https://stackoverflow.com/a/33762001/2492801. – Benjamin Bihler Aug 26 '19 at 09:19
3

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).

So, while Googling :) I found a great tool - FAR (Find And Replace) (not FART).

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).

jeb
  • 70,992
  • 15
  • 159
  • 202
madcorp
  • 321
  • 2
  • 6
  • It's the same answer as the answer from 2010 @VonC [In this thread](http://stackoverflow.com/a/2363075/463115) – jeb Aug 04 '15 at 15:00
  • @jeb I pointed that [FAR](http://findandreplace.sourceforge.net/) is not [FART](http://fart-it.sourceforge.net/) - two different programs with almost identical names. FAR has GUI and can work with regex, while in comments below that [thread](http://stackoverflow.com/a/2363075/463115) people mention that FART doesn't support regex. – madcorp Aug 04 '15 at 15:11
3

Use powershell in .bat - for Windows 7+

encoding utf8 is optional, good for web sites

@echo off
set ffile='myfile.txt'
set fold='FOO'
set fnew='BAR'
powershell -Command "(gc %ffile%) -replace %fold%, %fnew% | Out-File %ffile% -encoding utf8"
Wagner Pereira
  • 834
  • 10
  • 11
2

@Rachel gave an excellent answer but here is a variation of it to read content to a powershell $data 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.

@REM ASCII=7bit ascii(no bom), UTF8=with bom marker
set cmd=^
  $old = '\$Param1\$'; ^
  $new = 'Value1'; ^
  [string[]]$data = Get-Content 'datafile.txt'; ^
  $data = $data -replace $old, $new; ^
  out-file -InputObject $data -encoding UTF8 -filepath 'datafile.txt';
powershell -NoLogo -Noninteractive -InputFormat none -Command "%cmd%"
Whome
  • 9,559
  • 6
  • 43
  • 59
2

This is one thing that batch scripting just does not do well.

The script morechilli linked to will work for some files, but unfortunately it will choke on ones which contain characters such as pipes and ampersands.

VBScript is a better built-in tool for this task. See this article for an example: http://www.microsoft.com/technet/scriptcenter/resources/qanda/feb05/hey0208.mspx

1

Download Cygwin (free) and use unix-like commands at the Windows command line.

Your best bet: sed

jm.
  • 22,356
  • 20
  • 72
  • 91
0

Can also see the Replace and ReplaceFilter tools at https://zoomicon.github.io/tranXform/ (source included). The 2nd one is a filter.

The tool that replaces strings in files is in VBScript (needs Windows Script Host [WSH] to run in old Windows versions)

The filter is probably not working with Unicode unless you recompile with latest Delphi (or with FreePascal/Lazarus)

George Birbilis
  • 2,295
  • 2
  • 25
  • 33
-5

I have faced this problem several times while coding under Visual C++. If 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.

Under Visual Studio: Edit -> Find and Replace In the opened dialog, select your folder and fill in "Find What" and "Replace With" boxes. Hope this will be helpful.

Nadjib
  • 27
  • 2
    Nadjib, your answer doesn't help the user because your assuming they are using software of which they make no mention. Please suggest an option that doesn't require software. – Aibrean Mar 25 '15 at 16:00
  • @Aibrean the answer is no use, but not for that reason, it's the entry point that is wrong. – Paul Jul 01 '15 at 08:32
  • This response does not deserve the downvotes. In a Windows environment, there aren't a lot of good options to solve the OP's problem. I happen to code in VS and found this to be an excellent answer, and saved me a ton of time hunting for another solution. Replaced 20k+ occurrences in over 2k files across 3 directories in less than a min. – Jason Aug 18 '20 at 13:44