如何使用Windows命令行环境查找和替换文件中的文本?

时间:2022-08-29 23:16:05

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?

我正在编写一个使用Windows命令行环境的批处理文件脚本,并希望在一个文件中改变某些文本的出现。与另一个(例如“FOO”)。“酒吧”)。最简单的方法是什么?内建函数吗?

26 个解决方案

#1


169  

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.

如果您在支持。net 2.0的Windows版本中,我将替换您的shell。PowerShell从命令行中为您提供。net的全部功能。也有许多命令的构建。下面的示例将解决您的问题。我使用的是命令的全名,有更短的别名,但是这给了你一些谷歌的东西。

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

#2


167  

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:

我有Windows 7,内置了PowerShell。这里是我用来查找/替换文件中的所有文本实例的脚本:

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

To explain it:

解释:

  • powershell starts up powershell.exe, which is included in Windows 7
  • powershell powershell启动。exe,包括在Windows 7中。
  • -Command "... " is a command line arg for powershell.exe containing the command to run
  • - command”…是powershell的命令行arg。包含要运行的命令的exe。
  • (gc myFile.txt) reads the content of myFile.txt (gc is short for the Get-Content command)
  • (gc myFile.txt)读取myFile的内容。txt (gc是Get-Content命令的缩写)
  • -replace 'foo', 'bar' simply runs the replace command to replace foo with bar
  • -替换“foo”,“bar”只是运行替换命令,用bar替换foo。
  • | Out-File myFile.txt pipes the output to the file myFile.txt
  • | Out-File myFile。txt将输出输出到文件myFile.txt。

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

Powershell。exe应该是您的PATH语句的一部分,但是如果您不能添加它。它的位置在我的机器上是C:\WINDOWS\system32\ WindowsPowerShell \ v1.0

#3


141  

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.

使用FART(“F ind A nd R eplace T ext”命令行实用程序):在大量文件中用于文本替换的优秀的小免费软件。

The setup files are on SourceForge.

安装文件在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.

将在这个Perl发行版的文件中进行递归的预览。

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

唯一的问题:FART网站的图标不是很有品位,优雅或优雅;


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ç

更新2017年(7年之后)jagb在2011年的文章中指出“放轻松的方法-找到并替换文本”,从Mikail Tunc。

#4


108  

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.

替换——用字符串替换描述替换一个子字符串:用另一个字符串替换子字符串使用字符串替换特性。这里显示的示例将使用字符串变量str中的“The”替换所有出现的“teh”拼写错误。

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

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

#5


50  

Create file replace.vbs:

创建文件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:

要使用这个修改后的脚本(我们将调用replace.vbs),只需在命令提示符中键入类似于此的命令:

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

cscript替换。根据“C:\脚本\文本。"吉姆" "詹姆斯"

#6


46  

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

BatchSubstitute。bat on dos.com是一个搜索和替换使用纯批处理文件的例子。

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

它使用了FOR, FIND和CALL SET的组合。

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

行包含字符之间“& < > | ^可能错误地对待。


#7


35  

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!!!!

注意:一定要在这个答案的末尾看到与上级JREPL的链接的更新。蝙蝠取代REPL。蝙蝠JREPL。BAT 7.0和以上本地支持unicode (UTF- 16le)通过/UTF选项,以及任何其他字符集,包括UTF-8,通过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的小型混合JScript/batch实用程序。BAT对于通过命令行或批处理文件修改ASCII(或扩展的ASCII)文件非常方便。纯本机脚本不需要安装任何第三方可执行文件,而且它适用于从XP开始的任何现代Windows版本。它也非常快,特别是与纯批解决方案相比。

REPL.BAT simply reads stdin, performs a JScript regex search and replace, and writes the result to stdout.

REPL。BAT只是读取stdin,执行JScript regex搜索和替换,并将结果写入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:

下面是一个简单的例子,说明如何在测试中替换foo。txt,假设REPL。BAT在你当前的文件夹中,或者更好的是,在你的路径中的某个地方:

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.

JScript regex功能使它非常强大,特别是替换文本可以从搜索文本中引用捕获的子字符串的能力。

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.

我已经在实用程序中加入了一些选项,使它变得非常强大。例如,结合M和X选项可以修改二进制文件!M多行选项允许跨多个行进行搜索。X扩展替换模式选项提供了转义序列,可以在替换文本中包含任何二进制值。

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.

整个实用程序可以写成纯JScript,但是混合批处理文件消除了每次想要使用该实用程序时显式指定CSCRIPT的需要。

Here is the REPL.BAT script. Full documentation is embedded within the script.

这是REPL。蝙蝠脚本。完整的文档嵌入在脚本中。

@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:

我已停止开发REPL。蝙蝠,然后用JREPL.BAT代替它。这个新的实用程序具有所有相同的REPL功能。蝙蝠,加上更多的:

  • Unicode UTF-16LE support via native CSCRIPT unicode capabilities, and any other character set (including UTF-8) via ADO.
  • 使用本地CSCRIPT Unicode功能支持Unicode UTF-16LE,以及通过ADO的任何其他字符集(包括UTF-8)。
  • Read directly from / write directly to a file: no need for pipes, redirection, or move command.
  • 直接从/写到文件:不需要管道,重定向,或移动命令。
  • Incorporate user supplied JScript
  • 将用户提供的JScript
  • Translation facility similar to unix tr, only it also supports regex search and JScript replace
  • 与unix tr类似的翻译工具,也只支持regex搜索和JScript替换。
  • 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.

JREPL的当前版本。在DosTips中可用BAT。阅读线程中的所有后续文章,以查看使用示例和开发历史。

#8


29  

Use FNR

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

使用fnr效用。它比放屁有一些优势:

  • Regular expressions
  • 正则表达式
  • Optional GUI. Has a "Generate command line button" to create command line text to put in batch file.
  • 可选的GUI。有一个“生成命令行按钮”来创建命令行文本,以放入批处理文件。
  • Multi-line patterns: The GUI allows you to easily work with multi-line patterns. In FART you'd have to manually escape line breaks.
  • 多行模式:GUI允许您轻松地使用多行模式。在放屁时,你必须手动换行。
  • Allows you to select text file encoding. Also has an auto detect option.
  • 允许您选择文本文件编码。还有一个自动检测选项。

Download FNR here: http://findandreplace.codeplex.com/

在这里下载FNR:http://findandreplace.codeplex.com/

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

使用示例:fnr——cl——dir“ <目录路径> ”——fileMask“hibernate”。-useRegEx—找到“find_str_expression”—替换“replace_string”

#9


23  

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

我不认为有什么方法可以使用任何内置命令。我建议您下载Gnuwin32或UnxUtils之类的东西,并使用sed命令(或仅下载sed):

sed -c s/FOO/BAR/g filename

#10


15  

I know I am late to the party..

我知道我迟到了。

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

就我个人而言,我喜欢这个解决方案:http://www.dospecs.com/dttipsstring操纵。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

我们还广泛使用Dedupe功能,以帮助我们每天通过SMTP发送大约500封电子邮件:- https://groups.google.com/forum/#!

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

去复印机(注意:ABA号的使用-9):

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!

谢谢!

#11


13  

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.

当您在Windows上使用Git时,只需启动Git -bash并使用sed。或者,在使用Windows 10时,在Windows上启动“Ubuntu on Windows”(Linux子系统),并使用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.
  • -i选项用于在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.
    • s被用来替换找到的表达式“foo”和“bar”,而g被用来替换任何找到的匹配项。
  • -e选项指示要运行的命令。s被用来替换找到的表达式“foo”和“bar”,而g被用来替换任何找到的匹配项。

Note by ereOn:

注意ereOn:

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

如果您想要在版本化的文件中替换一个Git存储库中的字符串,您可能需要使用:

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

git -文件 <最终子文件夹&过滤> | xargs -i -e 's/foo/bar/g'

which works wonders.

它能创造奇迹。

#12


11  

I have used perl, and that works marvelously.

我已经使用了perl,而且效果非常好。

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

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

.orig是它将附加到原始文件的扩展。

For a number of files matching such as *.html

对于一些匹配的文件,例如*.html。

for %x in (<filePattern>) do perl -pi.orig -e "s/<textToReplace>/<textToReplaceWith>/g;" %x

#13


11  

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

这样做的好处是可以从任何程序输出输出。我们也会使用正则表达式。无法解决如何使它成为一个BAT文件,以便更容易使用…:-(

#14


10  

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

这是我在Win XP上找到的解决方案。在我的运行批处理文件中,包括以下内容:

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.

取代。bat文件如下。我没有找到在同一个批处理文件中包含该函数的方法,因为%%一个变量似乎总是在for循环中给出最后一个值。

replace.bat:

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

#15


10  

With the replacer.bat

与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":

1)与e ?可以评估特殊字符序列的选项,比如\n\r和unicode序列。在本例中,将替换引用的“Foo”和“Bar”:

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

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

2)直接替换没有引用Foo和Bar的地方。

call replacer.bat "C:\content.txt" "Foo" "Bar"

#16


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:

看一看cmd有什么类似于sed的实用工具。exe要求在Windows下使用sed等效项,也应适用于此问题。执行概要:

  • 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
  • 如果您拥有安装或复制exe的特权,那么许多可用的第三方可执行文件将为您完成。
  • Can be done with VBScript or similar if you need something able to run on a Windows box without modification etc.
  • 可以使用VBScript或类似的方法,如果您需要能够在Windows框上运行而不需要修改等等。

#17


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.

但是,您通常以各种形式使用FOR语句。有人创建了一个有用的批处理文件,可以进行搜索和替换。看看这里。了解批处理文件的局限性是很重要的。出于这个原因,我不会在这个答案中复制源代码。

#18


4  

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.

由Stack Overflow成员dbenham和aacini在Windows中使用本地内置的jscript编写了两个批处理文件,提供搜索和替换功能。

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.

与普通的批处理脚本相比,它们都是健壮且非常迅速的,而且对于基本的文本替换来说也更简单。它们都有Windows正则表达式模式匹配。

======================================================================================

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

1) Thissed-like helper batch file is called repl.bat (by dbenham) - download from: https://www.dropbox.com/s/qidqwztmetbvklt/repl.bat

1)这个类似的助手批处理文件叫做repl。bat (dbenham) -下载:https://www.dropbox.com/s/qidqwztmetbvklt/repl.bat。

Example using the L literal switch:

示例使用L文字转换:

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

2)这个类似grep的辅助批处理文件称为findrepl。bat (aacini) -下载: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.

当放置在路径上的文件夹中,或者可以在同一个文件夹中使用批处理文件,或者从cmd提示符中使用时,它们都成为强大的系统范围的实用工具。

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

它们都有不区分大小写的开关和许多其他功能。

#19


3  

Power shell command works like a charm

Power shell命令就像一个咒语。

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

#20


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

只是遇到了类似的问题——“在文件中搜索和替换文本”,但是对于文件名和搜索/repalce来说,我需要使用regex。因为我不熟悉Powershell并希望保存我的搜索以便以后使用,所以我需要一些更“用户友好”的东西(如果它有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).

这个小程序有很好的GUI,支持regex在文件名和文件中搜索。只有当你想保存你的设置时,你必须以管理员的身份运行程序(至少在Win7上)。

#21


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.

morechilli的脚本会对某些文件起作用,但不幸的是,它会被包含诸如管道和符号之类字符的文件阻塞。

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

VBScript是这个任务的更好的内置工具。请参阅本文的示例:http://www.microsoft.com/technet/scriptcenter/resources/qanda/feb05/hey0208.mspx。

#22


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.

@Rachel给出了一个很好的答案,但这里有一种变体,可以将内容读给powershell $data变量。在写入输出文件之前,您可以轻松地对内容进行多次操作。还可以看到在.bat批处理文件中如何给出多行值。

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

#23


1  

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

下载Cygwin(免费),并在Windows命令行使用类unix命令。

Your best bet: sed

你最好的选择:sed

#24


1  

Use powershell in .bat - for Windows 7+

在.bat中使用powershell,适用于Windows 7+。

encoding utf8 is optional, good for web sites

utf8编码是可选的,对web站点很好。

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

#25


0  

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

还可以在https://zoomicon.github中看到替换和替换过滤器工具。io / tranXform /(包括源代码)。第二个是过滤器。

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

在文件中替换字符串的工具是VBScript(需要Windows脚本主机[WSH]在旧Windows版本中运行)

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

除非您使用最新的Delphi(或使用FreePascal/Lazarus)重新编译,否则该过滤器可能不会使用Unicode。

#26


-6  

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.

在Visual c++中编写代码时,我多次遇到这个问题。如果有的话,可以使用Visual studio查找和替换实用程序。它允许您选择一个文件夹,并将该文件夹中的任何文件的内容替换为您想要的任何其他文本。

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.

在Visual Studio中:Edit ->在打开的对话框中找到并替换,选择你的文件夹并填写“查找什么”和“替换”框。希望这对你有帮助。

#1


169  

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.

如果您在支持。net 2.0的Windows版本中,我将替换您的shell。PowerShell从命令行中为您提供。net的全部功能。也有许多命令的构建。下面的示例将解决您的问题。我使用的是命令的全名,有更短的别名,但是这给了你一些谷歌的东西。

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

#2


167  

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:

我有Windows 7,内置了PowerShell。这里是我用来查找/替换文件中的所有文本实例的脚本:

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

To explain it:

解释:

  • powershell starts up powershell.exe, which is included in Windows 7
  • powershell powershell启动。exe,包括在Windows 7中。
  • -Command "... " is a command line arg for powershell.exe containing the command to run
  • - command”…是powershell的命令行arg。包含要运行的命令的exe。
  • (gc myFile.txt) reads the content of myFile.txt (gc is short for the Get-Content command)
  • (gc myFile.txt)读取myFile的内容。txt (gc是Get-Content命令的缩写)
  • -replace 'foo', 'bar' simply runs the replace command to replace foo with bar
  • -替换“foo”,“bar”只是运行替换命令,用bar替换foo。
  • | Out-File myFile.txt pipes the output to the file myFile.txt
  • | Out-File myFile。txt将输出输出到文件myFile.txt。

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

Powershell。exe应该是您的PATH语句的一部分,但是如果您不能添加它。它的位置在我的机器上是C:\WINDOWS\system32\ WindowsPowerShell \ v1.0

#3


141  

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.

使用FART(“F ind A nd R eplace T ext”命令行实用程序):在大量文件中用于文本替换的优秀的小免费软件。

The setup files are on SourceForge.

安装文件在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.

将在这个Perl发行版的文件中进行递归的预览。

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

唯一的问题:FART网站的图标不是很有品位,优雅或优雅;


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ç

更新2017年(7年之后)jagb在2011年的文章中指出“放轻松的方法-找到并替换文本”,从Mikail Tunc。

#4


108  

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.

替换——用字符串替换描述替换一个子字符串:用另一个字符串替换子字符串使用字符串替换特性。这里显示的示例将使用字符串变量str中的“The”替换所有出现的“teh”拼写错误。

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

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

#5


50  

Create file replace.vbs:

创建文件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:

要使用这个修改后的脚本(我们将调用replace.vbs),只需在命令提示符中键入类似于此的命令:

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

cscript替换。根据“C:\脚本\文本。"吉姆" "詹姆斯"

#6


46  

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

BatchSubstitute。bat on dos.com是一个搜索和替换使用纯批处理文件的例子。

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

它使用了FOR, FIND和CALL SET的组合。

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

行包含字符之间“& < > | ^可能错误地对待。


#7


35  

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!!!!

注意:一定要在这个答案的末尾看到与上级JREPL的链接的更新。蝙蝠取代REPL。蝙蝠JREPL。BAT 7.0和以上本地支持unicode (UTF- 16le)通过/UTF选项,以及任何其他字符集,包括UTF-8,通过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的小型混合JScript/batch实用程序。BAT对于通过命令行或批处理文件修改ASCII(或扩展的ASCII)文件非常方便。纯本机脚本不需要安装任何第三方可执行文件,而且它适用于从XP开始的任何现代Windows版本。它也非常快,特别是与纯批解决方案相比。

REPL.BAT simply reads stdin, performs a JScript regex search and replace, and writes the result to stdout.

REPL。BAT只是读取stdin,执行JScript regex搜索和替换,并将结果写入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:

下面是一个简单的例子,说明如何在测试中替换foo。txt,假设REPL。BAT在你当前的文件夹中,或者更好的是,在你的路径中的某个地方:

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.

JScript regex功能使它非常强大,特别是替换文本可以从搜索文本中引用捕获的子字符串的能力。

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.

我已经在实用程序中加入了一些选项,使它变得非常强大。例如,结合M和X选项可以修改二进制文件!M多行选项允许跨多个行进行搜索。X扩展替换模式选项提供了转义序列,可以在替换文本中包含任何二进制值。

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.

整个实用程序可以写成纯JScript,但是混合批处理文件消除了每次想要使用该实用程序时显式指定CSCRIPT的需要。

Here is the REPL.BAT script. Full documentation is embedded within the script.

这是REPL。蝙蝠脚本。完整的文档嵌入在脚本中。

@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:

我已停止开发REPL。蝙蝠,然后用JREPL.BAT代替它。这个新的实用程序具有所有相同的REPL功能。蝙蝠,加上更多的:

  • Unicode UTF-16LE support via native CSCRIPT unicode capabilities, and any other character set (including UTF-8) via ADO.
  • 使用本地CSCRIPT Unicode功能支持Unicode UTF-16LE,以及通过ADO的任何其他字符集(包括UTF-8)。
  • Read directly from / write directly to a file: no need for pipes, redirection, or move command.
  • 直接从/写到文件:不需要管道,重定向,或移动命令。
  • Incorporate user supplied JScript
  • 将用户提供的JScript
  • Translation facility similar to unix tr, only it also supports regex search and JScript replace
  • 与unix tr类似的翻译工具,也只支持regex搜索和JScript替换。
  • 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.

JREPL的当前版本。在DosTips中可用BAT。阅读线程中的所有后续文章,以查看使用示例和开发历史。

#8


29  

Use FNR

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

使用fnr效用。它比放屁有一些优势:

  • Regular expressions
  • 正则表达式
  • Optional GUI. Has a "Generate command line button" to create command line text to put in batch file.
  • 可选的GUI。有一个“生成命令行按钮”来创建命令行文本,以放入批处理文件。
  • Multi-line patterns: The GUI allows you to easily work with multi-line patterns. In FART you'd have to manually escape line breaks.
  • 多行模式:GUI允许您轻松地使用多行模式。在放屁时,你必须手动换行。
  • Allows you to select text file encoding. Also has an auto detect option.
  • 允许您选择文本文件编码。还有一个自动检测选项。

Download FNR here: http://findandreplace.codeplex.com/

在这里下载FNR:http://findandreplace.codeplex.com/

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

使用示例:fnr——cl——dir“ <目录路径> ”——fileMask“hibernate”。-useRegEx—找到“find_str_expression”—替换“replace_string”

#9


23  

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

我不认为有什么方法可以使用任何内置命令。我建议您下载Gnuwin32或UnxUtils之类的东西,并使用sed命令(或仅下载sed):

sed -c s/FOO/BAR/g filename

#10


15  

I know I am late to the party..

我知道我迟到了。

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

就我个人而言,我喜欢这个解决方案:http://www.dospecs.com/dttipsstring操纵。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

我们还广泛使用Dedupe功能,以帮助我们每天通过SMTP发送大约500封电子邮件:- https://groups.google.com/forum/#!

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

去复印机(注意:ABA号的使用-9):

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!

谢谢!

#11


13  

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.

当您在Windows上使用Git时,只需启动Git -bash并使用sed。或者,在使用Windows 10时,在Windows上启动“Ubuntu on Windows”(Linux子系统),并使用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.
  • -i选项用于在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.
    • s被用来替换找到的表达式“foo”和“bar”,而g被用来替换任何找到的匹配项。
  • -e选项指示要运行的命令。s被用来替换找到的表达式“foo”和“bar”,而g被用来替换任何找到的匹配项。

Note by ereOn:

注意ereOn:

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

如果您想要在版本化的文件中替换一个Git存储库中的字符串,您可能需要使用:

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

git -文件 <最终子文件夹&过滤> | xargs -i -e 's/foo/bar/g'

which works wonders.

它能创造奇迹。

#12


11  

I have used perl, and that works marvelously.

我已经使用了perl,而且效果非常好。

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

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

.orig是它将附加到原始文件的扩展。

For a number of files matching such as *.html

对于一些匹配的文件,例如*.html。

for %x in (<filePattern>) do perl -pi.orig -e "s/<textToReplace>/<textToReplaceWith>/g;" %x

#13


11  

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

这样做的好处是可以从任何程序输出输出。我们也会使用正则表达式。无法解决如何使它成为一个BAT文件,以便更容易使用…:-(

#14


10  

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

这是我在Win XP上找到的解决方案。在我的运行批处理文件中,包括以下内容:

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.

取代。bat文件如下。我没有找到在同一个批处理文件中包含该函数的方法,因为%%一个变量似乎总是在for循环中给出最后一个值。

replace.bat:

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

#15


10  

With the replacer.bat

与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":

1)与e ?可以评估特殊字符序列的选项,比如\n\r和unicode序列。在本例中,将替换引用的“Foo”和“Bar”:

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

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

2)直接替换没有引用Foo和Bar的地方。

call replacer.bat "C:\content.txt" "Foo" "Bar"

#16


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:

看一看cmd有什么类似于sed的实用工具。exe要求在Windows下使用sed等效项,也应适用于此问题。执行概要:

  • 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
  • 如果您拥有安装或复制exe的特权,那么许多可用的第三方可执行文件将为您完成。
  • Can be done with VBScript or similar if you need something able to run on a Windows box without modification etc.
  • 可以使用VBScript或类似的方法,如果您需要能够在Windows框上运行而不需要修改等等。

#17


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.

但是,您通常以各种形式使用FOR语句。有人创建了一个有用的批处理文件,可以进行搜索和替换。看看这里。了解批处理文件的局限性是很重要的。出于这个原因,我不会在这个答案中复制源代码。

#18


4  

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.

由Stack Overflow成员dbenham和aacini在Windows中使用本地内置的jscript编写了两个批处理文件,提供搜索和替换功能。

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.

与普通的批处理脚本相比,它们都是健壮且非常迅速的,而且对于基本的文本替换来说也更简单。它们都有Windows正则表达式模式匹配。

======================================================================================

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

1) Thissed-like helper batch file is called repl.bat (by dbenham) - download from: https://www.dropbox.com/s/qidqwztmetbvklt/repl.bat

1)这个类似的助手批处理文件叫做repl。bat (dbenham) -下载:https://www.dropbox.com/s/qidqwztmetbvklt/repl.bat。

Example using the L literal switch:

示例使用L文字转换:

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

2)这个类似grep的辅助批处理文件称为findrepl。bat (aacini) -下载: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.

当放置在路径上的文件夹中,或者可以在同一个文件夹中使用批处理文件,或者从cmd提示符中使用时,它们都成为强大的系统范围的实用工具。

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

它们都有不区分大小写的开关和许多其他功能。

#19


3  

Power shell command works like a charm

Power shell命令就像一个咒语。

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

#20


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

只是遇到了类似的问题——“在文件中搜索和替换文本”,但是对于文件名和搜索/repalce来说,我需要使用regex。因为我不熟悉Powershell并希望保存我的搜索以便以后使用,所以我需要一些更“用户友好”的东西(如果它有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).

这个小程序有很好的GUI,支持regex在文件名和文件中搜索。只有当你想保存你的设置时,你必须以管理员的身份运行程序(至少在Win7上)。

#21


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.

morechilli的脚本会对某些文件起作用,但不幸的是,它会被包含诸如管道和符号之类字符的文件阻塞。

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

VBScript是这个任务的更好的内置工具。请参阅本文的示例:http://www.microsoft.com/technet/scriptcenter/resources/qanda/feb05/hey0208.mspx。

#22


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.

@Rachel给出了一个很好的答案,但这里有一种变体,可以将内容读给powershell $data变量。在写入输出文件之前,您可以轻松地对内容进行多次操作。还可以看到在.bat批处理文件中如何给出多行值。

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

#23


1  

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

下载Cygwin(免费),并在Windows命令行使用类unix命令。

Your best bet: sed

你最好的选择:sed

#24


1  

Use powershell in .bat - for Windows 7+

在.bat中使用powershell,适用于Windows 7+。

encoding utf8 is optional, good for web sites

utf8编码是可选的,对web站点很好。

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

#25


0  

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

还可以在https://zoomicon.github中看到替换和替换过滤器工具。io / tranXform /(包括源代码)。第二个是过滤器。

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

在文件中替换字符串的工具是VBScript(需要Windows脚本主机[WSH]在旧Windows版本中运行)

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

除非您使用最新的Delphi(或使用FreePascal/Lazarus)重新编译,否则该过滤器可能不会使用Unicode。

#26


-6  

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.

在Visual c++中编写代码时,我多次遇到这个问题。如果有的话,可以使用Visual studio查找和替换实用程序。它允许您选择一个文件夹,并将该文件夹中的任何文件的内容替换为您想要的任何其他文本。

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.

在Visual Studio中:Edit ->在打开的对话框中找到并替换,选择你的文件夹并填写“查找什么”和“替换”框。希望这对你有帮助。