Como você pode encontrar e replace texto em um arquivo usando o ambiente de linha de comando do Windows?

Eu estou escrevendo um script de arquivo em lotes usando o ambiente de linha de comando do Windows e deseja alterar cada ocorrência de algum texto em um arquivo (ex. “FOO”) com outro (ex. “BAR”). Qual é a maneira mais simples de fazer isso? Qualquer construído em funções?

Se você estiver na versão do Windows que suporta .Net 2.0, eu iria replace o seu shell. O PowerShell oferece todo o poder do .Net a partir da linha de comando. Existem muitos commandlets embutidos também. O exemplo abaixo resolverá sua questão. Estou usando os nomes completos dos comandos, há aliases mais curtos, mas isso dá a você algo para o Google.

(Get-Content test.txt) | ForEach-Object { $_ -replace "foo", "bar" } | Set-Content test2.txt 

Muitas das respostas aqui ajudaram a me apontar na direção certa, mas nenhuma foi adequada para mim, então estou postando minha solução.

Eu tenho o Windows 7, que vem com o PowerShell embutido. Aqui está o script que usei para encontrar / replace todas as instâncias do texto em um arquivo:

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

Para explicar isso:

  • powershell iniciado powershell.exe, que está incluído no Windows 7
  • -Command "... " é um arg de linha de comando para powershell.exe contendo o comando para executar
  • (gc myFile.txt) lê o conteúdo de myFile.txt ( gc é abreviação do comando Get-Content )
  • -replace 'foo', 'bar' simplesmente executa o comando replace para replace foo por bar
  • | Out-File myFile.txt | Out-File myFile.txt canaliza a saída para o arquivo myFile.txt

O Powershell.exe já deve fazer parte da sua declaração PATH, mas se não, você pode adicioná-lo. A localização dele na minha máquina é C:\WINDOWS\system32\WindowsPowerShell\v1.0

Apenas usei o utilitário de linha de comando FART (” F ind A nd R eplace T ext”):
excelente pequeno freeware para substituição de texto em um grande conjunto de arquivos.

Os arquivos de configuração estão no SourceForge .

Exemplo de uso:

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

irá visualizar as substituições para fazer recursivamente nos arquivos desta distribuição Perl.

Único problema: o ícone do site da FART não é exatamente de bom gosto, refinado ou elegante;)


Atualização 2017 (7 anos depois) jagb aponta nos comentários ao artigo de 2011 ” FARTing the Easy Way – Encontre e Substitua Texto ” do Mikail Tunç

Substituir – Substituir uma substring usando a substituição de string Descrição: Para replace uma substring por outra string, use o recurso de substituição de string. O exemplo mostrado aqui substitui todas as ocorrências “teh” erros de ortografia com “o” na variável string str.

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

Saída de Script:

 teh cat in teh hat the cat in the hat 

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

Crie o arquivo 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 

Para usar este script revisado (que chamaremos de replace.vbs), basta digitar um comando semelhante a este no prompt de comando:

cscript replace.vbs "C:\Scripts\Text.txt" "Jim " "James "

BatchSubstitute.bat em dostips.com é um exemplo de pesquisa e substituição usando um arquivo de lote puro.

Utiliza uma combinação de FOR , FIND e CALL SET .

Linhas contendo caracteres entre "&<>]|^ podem ser tratadas incorretamente.


Nota – Certifique-se de ver a atualização no final desta resposta para um link para o superior JREPL.BAT que substitui o REPL.BAT
O JREPL.BAT 7.0 e superior suporta nativamente o unicode (UTF-16LE) através da opção /UTF , assim como qualquer outro conjunto de caracteres, incluindo o UTF-8, via ADO !!!!


Eu escrevi um pequeno utilitário híbrido JScript / batch chamado REPL.BAT que é muito conveniente para modificar arquivos ASCII (ou ASCII estendido) via linha de comando ou um arquivo de lote. O script puramente nativo não requer instalação de qualquer terceiro executável, e funciona em qualquer versão moderna do Windows a partir do XP. Também é muito rápido, especialmente quando comparado a soluções de lote puro.

REPL.BAT simplesmente lê stdin, executa uma pesquisa e substituição de regex do JScript e grava o resultado em stdout.

Aqui está um exemplo trivial de como replace o foo por bar no test.txt, assumindo que o REPL.BAT está na sua pasta atual, ou melhor ainda, em algum lugar dentro do seu PATH:

 type test.txt|repl "foo" "bar" >test.txt.new move /y test.txt.new test.txt 

Os resources de regex do JScript o tornam muito poderoso, especialmente a capacidade do texto de substituição de referenciar substrings capturadas a partir do texto de pesquisa.

Eu incluí um número de opções no utilitário que o tornam bastante poderoso. Por exemplo, combinar as opções M e X permite a modificação de arquivos binários! A opção M Multi-line permite pesquisas em várias linhas. A opção de padrão de substituição X eXtended fornece seqüências de escape que permitem a inclusão de qualquer valor binário no texto de substituição.

O utilitário inteiro poderia ter sido escrito como JScript puro, mas o arquivo em lote híbrido elimina a necessidade de especificar explicitamente o CSCRIPT toda vez que você quiser usar o utilitário.

Aqui está o script REPL.BAT. A documentação completa está incorporada no 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)); } 

ATUALIZAÇÃO IMPORTANTE

Eu parei o desenvolvimento de REPL.BAT e substituí-lo com JREPL.BAT. Este novo utilitário tem a mesma funcionalidade do REPL.BAT, além de muito mais:

  • Unicode UTF-16LE suporte via capacidades de unicode CSCRIPT nativas, e qualquer outro conjunto de caracteres (incluindo UTF-8) via ADO.
  • Leia diretamente de / write diretamente para um arquivo: não há necessidade de pipes, redirecionamento ou comando de movimentação.
  • Incorporar JScript fornecido pelo usuário
  • Recurso de tradução semelhante ao unix tr, apenas ele também suporta pesquisa regex e substituição de JScript
  • Descartar texto não correspondente
  • Linhas de saída de prefixo com número de linha
  • e mais…

Como sempre, a documentação completa está incorporada no script.

A solução trivial original é agora ainda mais simples:

 jrepl "foo" "bar" /f test.txt /o - 

A versão atual do JREPL.BAT está disponível no DosTips . Leia todos os posts subseqüentes no thread para ver exemplos de uso e um histórico do desenvolvimento.

Use FNR

Use o utilitário fnr . Tem algumas vantagens sobre o fart :

  • Expressões regulares
  • GUI opcional. Tem um “botão de linha de comando Gerar” para criar texto de linha de comando para colocar em arquivo em lotes.
  • Padrões de várias linhas: a GUI permite que você trabalhe facilmente com padrões de várias linhas. No FART, você teria que escaping manualmente das quebras de linha.
  • Permite selecionar a codificação do arquivo de texto. Também tem uma opção de detecção automática.

Faça o download do FNR aqui: http://findandreplace.codeplex.com/

Exemplo de uso: fnr --cl --dir "" --fileMask "hibernate.*" --useRegEx --find "find_str_expression" --replace "replace_string"

Eu não acho que haja uma maneira de fazer isso com qualquer comando embutido. Eu sugiro que você baixe algo como Gnuwin32 ou UnxUtils e use o comando sed (ou baixe apenas sed ):

 sed -cs/FOO/BAR/g filename 

Eu sei que estou atrasado para a festa.

Pessoalmente, eu gosto da solução em: – http://www.dostips.com/DtTipsStringManipulation.php#Snippets.Replace

Nós também usamos extensivamente a Função Dedupe para nos ajudar a entregar aproximadamente 500 e-mails diariamente via SMTP a partir de: – https://groups.google.com/forum/#!topic/alt.msdos.batch.nt/sj8IUhMOq6o

e ambos funcionam nativamente sem ferramentas extras ou utilidades necessárias.

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 

DEDUPLICADOR (observe o uso de -9 para um número ABA):

 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 

Obrigado!

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 | xargs sed -i -e 's/foo/bar/g'

which works wonders.

I have used perl, and that works marvelously.

 perl -pi.orig -e "s///g;"  

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

For a number of files matching such as *.html

 for %x in () do perl -pi.orig -e "s///g;" %x 

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… 🙁

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" 

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 

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. Sumário executivo:

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

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.

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) This sed-like helper batch file is called repl.bat (by dbenham) – download from: https://www.dropbox.com/s/qidqwztmetbvklt/repl.bat

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) – download from: https://www.dropbox.com/s/rfdldmcb6vwi9xc/findrepl.bat

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.

Power shell command works like a charm

 ( test.txt | ForEach-Object { $_ -replace "foo", "bar" } | Set-Content test2.txt ) 

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

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

@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%" 

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

Your best bet: sed

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" 

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)

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.