当前位置:  开发笔记 > 开发工具 > 正文

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

如何解决《如何使用Windows命令行环境查找和替换文件中的文本?》经验,为你挑选了16个好方法。

我正在使用Windows命令行环境编写批处理文件脚本,并希望将文件中某些文本(例如"FOO")的每次出现更改为另一个(例如"BAR").最简单的方法是什么?任何内置功能?



1> Rachel..:

这里的很多答案帮助我指出了正确的方向,但是没有一个适合我,所以我发布了我的解决方案.

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

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

解释一下:

powershell 启动powershell.exe,它包含在Windows 7中

-Command "... " 是powershell.exe的命令行arg,包含要运行的命令

(gc myFile.txt)读取内容myFile.txt(gcGet-Content命令的缩写)

-replace 'foo', 'bar'只需运行replace命令替换foobar

| Out-File myFile.txt 将输出传递给文件 myFile.txt

Powershell.exe应该已经成为PATH语句的一部分,但如果没有,您可以添加它.它在我的机器上的位置是-encoding ASCII


@Wyck我花了一段时间才弄清楚`-encoding ASCII`的位置.对于将来需要它的人来说,它将是"Out-File -encoding ASCII myFile.txt"
请注意,此命令也可以将文件转码为Unicode编码.您可以通过添加`-encoding ASCII`或`UTF8`或任何需要的内容来手动指定编码.另外要注意,如果你的目标是UTF8,它可能会在文件的开头引入一个没有出现在原文中的字节顺序标记.
请注意,替换标记(在这种情况下为"foo")被视为正则表达式.如果你有任何特殊字符(我有[]),你需要在前面添加一个\(反斜杠).
我唯一需要改变的是使用`Set-Content`而不是`Out-File`.
这有效,但即使是一个简短的文件列表,性能也很糟糕.
要转义特殊字符,还可以在正则表达式中使用"foo-bar"(撇号).

2> Mike Schall..:

如果您使用的是支持.Net 2.0的Windows版本,我会替换您的shell. PowerShell通过命令行为您提供.Net的全部功能.内置了许多命令行开关.以下示例将解决您的问题.我正在使用命令的全名,有更短的别名,但这给了你一些谷歌的东西.

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


-1 ..当然答案被接受了,但它不能回答指定的问题.
如果保存到同一文件,则会因文件正在使用而失败.您需要将powershell命令更改为:(Get-Content test.txt)| ForEach-Object {$ _ -replace"foo","bar"} | Set-Content test.txt
我可以看到PowerShell能够实现这一目标.但是如何从批处理文件中运行(例如:myProc.bat)?
请参阅@Rachel的答案:`powershell -Command"(gc myFile.txt)-replace'foo','bar'| sc myFile.txt"`
@Pablo,使用powershell.exe并将ps命令包装到单个参数中
我第二次投票给PowerShell.它为您提供了一个非常强大的shell.
@gareththegeek你有一个错误的假设.Powershell不需要提升权限.我这样说是为了让未来的读者知道这一点.
@royinamir:看起来在获取内容周围添加括号可能会解决问题吗?对不起,现在没有电脑可以测试... http://stackoverflow.com/questions/10239702/powershell-set-content-having-issues-with-file-already-in-use
如何对给定扩展名的目录中的所有文件执行此操作?

3> VonC..:

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

安装文件位于SourceForge上.

用法示例:

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

将预览替换以在此Perl发行版的文件中递归执行.

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


更新2017年(7年后)jagb指出在评论到2011年的文章" 放屁的简易方法-查找和替换文本 ",从MikailTunç


很酷的是它是一个单独的exe.没有依赖.不小的打印.超级易于部署.
谢谢,它是完美的,应该是标准dos工具的一部分,并有一个魅力.然而-p选项并没有显示它将会发生多少变化,并且总是会报告0,它让我几分钟
@jagb谢谢.我已将您的链接包含在答案中以获得更多可见性.
我知道这是一个非常古老的问题,但我发现了更多信息,希望它对Stack Overflow用户有所帮助.只是FART的另一个链接,其产品得到了很好的解释:[FART解释@ emtunc.org](https://emtunc.org/blog/03/2011/farting-the-easy-way-find-and-replace-text/ )和另一个页面可以在这里找到:[FART](http://fart-it.sourceforge.net/)**请小心替换`/`和`'`因为这不适用于所有我们**,对我来说它的工作在某些情况下,但它并没有对一些文件工作,我不知道为什么..我用这个与其他文本替换文本和`/`
非常轻巧,易于使用,但我希望它能打印出替换发生的确切位置.无法看到这让我感到不安全感.

4> 小智..:

替换 - 使用字符串替换替换子字符串描述:要使用另一个字符串替换子字符串,请使用字符串替换功能.这里显示的示例用字符串变量str中的"the"替换所有出现的"teh"拼写错误.

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

脚本输出:

teh cat in teh hat
the cat in the hat

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


sed建议如何更好?这似乎是他们所有人中最简单的答案,并且不需要安装任何东西.
"sed建议如何更好?" - sed和类似的实用程序对文件进行操作; 此代码段省略了从输入文件中读取行并写入输出文件的重要步骤,同时确保正确处理文件中的任何特殊字符.
@Asad,是的,这是真的,OP询问文件,但实际上它适用于不必是文件的流.但我的观点是,这个答案存在缺陷,因为它忽略了从流中读取/写入并处理任何特殊字符.
可以在这里完成任何类型的模式匹配吗?通配符,正则表达式等?
@Bill如何使用变量作为替换文本?即.我有一个变量值和一个有一些分隔符的字符串.set str =%str:"##"=%varValue %%不起作用.任何解决方法?
好的,这会替换环境变量中的文本,但如何使用它来替换文件的内容?

5> user459118..:

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

要使用这个修改过的脚本(我们称之为replace.vbs),只需在命令提示符下键入与此类似的命令:

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


@ user280109是的,VBScript支持`RegExp`.您可以使用它来替换使用正则表达式:`With(New RegExp):strNewText = .Replace(strText,strOldText,strNewText):End with`.您可以使用`$ 1`,`$ 2` ...`$ 9`获取前9个捕获组的文本.
VBScript经常被忽视(并且讨厌),但是在所有Windows平台上都可用,非常易读且实际上具有非常强大的功能+1

6> morechilli..:

BatchSubstitute.bat在dostips.com上是使用纯批处理文件进行搜索和替换的示例.

它采用的组合FOR,FINDCALL SET.

包含字符的行"&<>]|^可能会被错误地处理.



我不得不质疑代码片段的有用性,其[使用条款](http://www.dostips.com/DtGeneTermsOfUse.php)禁止复制任何代码("您不得分发在域名下提供的任何信息dostips.com以任何形式未经域名所有者明确书面许可.").
这很棒.我喜欢那些不涉及下载其他内容的答案.
"find:invalid predicate`'"错误是由于我的系统上有一个外部'find'实用程序.一旦删除,这工作正常.

7> dbenham..:

- 请务必查看本答案末尾的更新,以获取指向优先级JREPL.BAT的链接,该JREPL.BAT取代REPL.BAT
JREPL.BAT 7.0及以上版本通过该/UTF选项本机支持unicode(UTF-16LE),以及任何其他字符集,包括UTF-8,通过ADO !!!!


我编写了一个名为REPL.BAT的小型混合JScript /批处理实用程序,它非常便于通过命令行或批处理文件修改ASCII(或扩展ASCII)文件.纯粹的本机脚本不需要安装任何可执行的第三方,并且它适用于从XP开始的任何现代Windows版本.它也非常快,特别是与纯批量解决方案相比时.

REPL.BAT只读取stdin,执行JScr​​ipt正则表达式搜索和替换,并将结果写入stdout.

这里有一个简单的例子,说明如何在test.txt中用bar替换foo,假设REPL.BAT在你当前的文件夹中,或者更好,在你的PATH中的某个地方:

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

JScript正则表达式功能使其功能非常强大,尤其是替换文本从搜索文本中引用捕获的子字符串的能力.

我在实用程序中包含了许多选项,使其功能非常强大.例如,组合MX选项可以修改二进制文件!在M多行选项允许跨多行搜索.的X扩展取代模式选项提供了逸出,使包含在所述替代文本的任何二进制值的序列.

整个实用程序可以编写为纯JScript,但混合批处理文件无需在每次要使用该实用程序时显式指定CSCRIPT.

这是REPL.BAT脚本.完整文档嵌入在脚本中.

@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));
}


重要更新

我已停止开发REPL.BAT,并将其替换为JREPL.BAT.这个较新的实用程序具有REPL.BAT的所有相同功能,还有更多:

Unicode UTF-16LE支持通过本机CSCRIPT unicode功能,以及通过ADO的任何其他字符集(包括UTF-8).

直接从/直接读取文件:不需要管道,重定向或移动命令.

合并用户提供的JScript

翻译工具类似于unix tr,只有它还支持正则表达式搜索和JScript替换

丢弃不匹配的文字

前缀输出行与行号

和更多...

与往常一样,完整的文档嵌入在脚本中.

最初的简单解决方案现在更简单:

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

当前版本的JREPL.BAT可在DosTips上获得.阅读该主题中的所有后续帖子,以查看使用示例和开发历史.


@dbenham这是一个宝石.你为什么不把它放在GitHub上或作为一个要点?将进行版本控制,后续跟踪,发布/分发,修复和更容易.如果您需要帮助,请告诉我.

8> Aman..:
使用FNR

使用该fnr实用程序.它有一些优势fart:

常用表达

可选的GUI.有一个"生成命令行按钮"来创建命令行文本以放入批处理文件.

多行模式:GUI允许您轻松使用多行模式.在FART中,您必须手动转义换行符.

允许您选择文本文件编码.还有一个自动检测选项.

在这里下载FNR:http://findandreplace.io/? z = codeplex

用法示例: fnr --cl --dir "" --fileMask "hibernate.*" --useRegEx --find "find_str_expression" --replace "replace_string"



9> Ferruccio..:

我不认为有任何方法可以使用任何内置命令.我建议你下载类似Gnuwin32或UnxUtils的东西并使用sed命令(或仅下载sed):

sed -c s/FOO/BAR/g filename


Gnuwin32和UnxUtils是为Windows构建的独立二进制文件.他们不依赖于cygwin.
使用cygwin(http://www.cygwin.com).这是实际安装Linux的下一个最好的事情.

10> Leptonator..:

我知道我迟到了.

就个人而言,我喜欢以下解决方案: - http://www.dostips.com/DtTipsStringManipulation.php#Snippets.Replace

我们还广泛使用重复数据删除功能帮助我们每天通过SMTP发送大约500封电子邮件: - https://groups.google.com/forum/#!topic/alt.msdos.batch.nt/sj8IUhMOq6o

这些都是本地工作,不需要额外的工具或实用程序.

替代品:

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(注意使用-9表示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

谢谢!


@specializt - 请...我不是在这里讨论语义.如果您愿意,我们可以将其脱机进入聊天室.
我认为,*这*是原始问题的答案。我将使用此技巧在安装过程中为服务配置初始化文件,并且我不想启用PowerShell,也不想允许脚本引擎在我的服务器上运行。经常回答与Windows有关的问题,从“从那里安装此Gizmo”开始,因为周围仍然存在“ PC”态度。

11> Jens A. Koch..:

当您在Windows上使用Git时,只需启动git-bash 并使用即可sed.或者,在使用Windows 10时,启动"在Windows上使用Ubuntu进行Bash"(来自Linux子系统)并使用sed.

它是一个流编辑器,但可以使用以下命令直接编辑文件:

sed -i -e 's/foo/bar/g' filename

-i 选项用于在文件名上进行编辑.

-e option表示要运行的命令.

s用于将找到的表达式"foo"替换为"bar",g用于替换任何找到的匹配项.


ereOn注意:

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

git ls-files | xargs sed -i -e 's/foo/bar/g'

这是奇迹.



12> 小智..:

我使用过perl,这非常有效.

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

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

对于许多匹配的文件,例如*.html

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



13> Simon East..:

我在这里玩了一些现有的答案,更喜欢我改进的解决方案......

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

或者如果要将输出再次保存到文件中......

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

这样做的好处是可以管理任何程序的输出.也会考虑使用正则表达式.无法解决如何将其变成BAT文件以便于使用... :-(


这是一个很好的解决方案.不幸的是,使用`type`意味着包含大于80个字符的所有行.太痛苦了.

14> npocmaka..:

使用 replacer.bat

1)使用e?选项来评估特殊字符序列\n\r和unicode序列.在这种情况下将替换引用"Foo""Bar":

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

2)直接替换引用FooBar不引用的地方.

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



15> 小智..:

这是我在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

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

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



16> Jay..:

看看是否有任何类似于cmd.exe的实用工具,它要求Windows下的sed等效,也应该适用于这个问题.执行摘要:

它可以在批处理文件中完成,但它并不漂亮

很多可用的第三方可执行文件,如果您可以安装或只是复制exe,可以为您完成

如果你需要能够在没有修改的情况下在Windows机器上运行的东西,可以用VBScript或类似的东西来完成.

推荐阅读
mobiledu2402851377
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有