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

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

1107853 次浏览

我不认为有任何内置命令可以做到这一点。我建议你下载像Gnuwin32UnxUtils这样的文件,然后使用sed命令(或者只下载sed):

sed -c s/FOO/BAR/g filename

如果你使用的是支持。net 2.0的Windows版本,我会替换掉你的shell。PowerShell从命令行提供了. net的全部功能。还内置了许多命令小程序。下面的例子将解决你的问题。我使用的是命令的全名,还有更短的别名,但这给了你谷歌的一些东西。

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

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

您最好的选择:sed

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

它使用了FORFINDCALL SET的组合。

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


这是批处理脚本做得不好的一点。

所链接的脚本morechilli可以用于某些文件,但不幸的是,它会阻塞那些包含管道和&号等字符的文件。

VBScript是一个更好的内置工具。请看这篇文章的例子: # EYZ0 < / p >

看看cmd.exe是否有类似sed的实用程序,它要求在Windows下有一个等效的sed,也应该适用于这个问题。执行概要:

  • 它可以在批处理文件中完成,但它并不漂亮
  • 如果你有足够的时间安装或复制一个exe文件,很多可用的第三方可执行文件都可以帮你完成
  • 可以用VBScript或类似的东西,如果你需要能够运行在Windows盒子没有修改等。

可能有点晚了,但我经常在寻找类似的东西,因为我不想经历让软件被批准的痛苦。

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

只是用了 ("F ind 一个 nd R eplace T ext"命令行实用程序):
优秀的小免费软件,用于大型文件中的文本替换

安装文件都在SourceForge上

使用的例子:

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

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

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


2017年更新(7年后)jagb指出在评论中到2011年的文章& 放屁的简单方法-找到和替换文本"从# EYZ3


正如的评论(2020年12月)中的乔的工作所指出的,如果你想替换&A,你需要使用引号,以确保&不会被shell解释:

fart in.txt "&A" "B"

下面是我在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循环中的最后一个值。

# EYZ0:

@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

Power shell命令的工作就像一个魅力

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

创建文件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),只需在命令提示符中键入类似于下面的命令:

# EYZ0

我用过perl,它的效果非常好。

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

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

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

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

Replace -使用字符串替换替换子字符串 描述:使用字符串替换特性将子字符串替换为另一个字符串。这里显示的例子将字符串变量str.

中所有出现的“teh”拼写错误替换为“The”
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

裁判:# EYZ0

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

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文件,以便更容易使用…: - (

使用FNR

使用fnr实用程序。它比fart有一些优势:

  • 正则表达式
  • 可选的GUI。有“生成命令行按钮”;创建要放入批处理文件的命令行文本。
  • 多行模式:GUI允许您轻松地使用多行模式。在《放屁》中,你必须手动转行。
  • 允许您选择文本文件编码。也有一个自动检测选项。

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

< p >使用例子: # EYZ0 < / p >
< p > # EYZ0 # EYZ1 < br > JREPL.BAT 7.0及以上版本通过/UTF选项原生支持unicode (UTF-16LE),以及任何其他字符集,包括UTF-8,通过ADO!!!!< / em >


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

bat只是读取stdin,执行JScript正则表达式搜索和替换,并将结果写入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 eXtended替换模式选项提供转义序列,允许在替换文本中包含任何二进制值。

整个实用程序可以写成纯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));
}
< p >
# EYZ0 < / >强

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

  • 通过原生CSCRIPT Unicode功能支持Unicode UTF-16LE,以及通过ADO支持任何其他字符集(包括UTF-8)。
  • 直接从文件读取/直接写入文件:不需要管道、重定向或移动命令。
  • 合并用户提供的JScript
  • 翻译工具类似于unix tr,只是它也支持regex搜索和JScript替换
  • 丢弃不匹配的文本
  • 带有行号的前缀输出行
  • 和更多的……

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

原来的简单解现在更简单了:

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

# EYZ0。阅读该线程中的所有后续帖子,以查看使用示例和开发历史。

这里的很多答案都帮我指明了正确的方向,但是没有一个适合我,所以我把我的解决方案贴出来。

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

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

解释一下:

  • powershell将启动Windows 7中包含的powershell.exe
  • -Command "... "是powershell.exe的命令行参数,包含要运行的命令
  • (gc myFile.txt)读取myFile.txt的内容(gcGet-Content命令的缩写)
  • -replace 'foo', 'bar'简单地运行replace命令将foo替换为bar
  • | Out-File myFile.txt将输出输出到文件myFile.txt
  • 正如注释所指出的,-encoding ASCII防止将输出文件转录为unicode

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

显然,现代windows系统内置了PowerShell,允许您直接使用

(Get-Content myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt

两个提供search and replace函数的批处理文件是由Stack Overflow成员dbenhamaacini在Windows中使用native built-in jscript编写的。

与普通批处理脚本相比,它们都是robustvery swift with large files,以及用于基本文本替换的simpler。它们都有Windows regular expression模式匹配。

  1. 这个sed-like帮助批处理文件被称为repl.bat(由dbenham)。

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

    Example which has regular expressions active:

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

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

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

我知道我迟到了。

就我个人而言,我喜欢以下的解决方案: - # EYZ0 < / p > 我们还广泛使用重复数据删除功能,帮助我们每天通过SMTP发送大约500封电子邮件: - # EYZ0 < / p >

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

替代者:

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

谢谢!

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

在Visual Studio: 编辑->查找和替换 在打开的对话框中,选择文件夹并填写“查找内容”和“替换为”框。 希望这对你有所帮助。< / p >

刚刚遇到了一个类似的问题-“搜索和替换文件中的文本”,但除了文件名和搜索/替换我都需要使用正则表达式。因为我不熟悉Powershell,想要保存我的搜索以供以后使用,所以我需要一些更“用户友好”的东西(如果它有GUI的话更可取)。

所以,在谷歌搜索:)时,我发现了一个很棒的工具——FAR(查找和替换)(不是屁)。

这个小程序有很好的GUI和支持正则表达式在文件名和文件内搜索。唯一的缺点是,如果你想保存你的设置,你必须以管理员身份运行程序(至少在Win7上)。

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"

当你使用Git on Windows时,简单地点燃git-bash 并使用sed。或者,当使用Windows 10时,启动“Bash on Ubuntu on Windows”(从Linux子系统)并使用sed.

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

sed -i -e 's/foo/bar/g' filename
  • -i选项用于在文件名上进行编辑。
  • -e option表示要执行的命令。
    • s用于将找到的表达式“foo”替换为“bar”,g用于替换任何找到的匹配项。
    • 李< / ul > < / >

    ereOn注:

    如果你只想替换Git存储库版本文件中的字符串,你可能想使用:

    # EYZ0

    这产生了奇迹。

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

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

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

除非你用最新的Delphi(或FreePascal/Lazarus)重新编译,否则过滤器可能无法使用Unicode。

在Windows 7+的。bat中使用powershell

编码utf8是可选的,适合网站

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

我更喜欢使用sedWin32的GNU实用程序,以下需要注意

  • 单引号''不能在windows中工作,使用""代替
  • sed -i不能在windows中工作,它需要文件交换

因此,sed在windows中查找和替换文件中的文本的工作代码如下所示

sed -e "s/foo/bar/g" test.txt > tmp.txt && mv tmp.txt test.txt

Powershell命令-

获取文件的内容,并将其替换为其他文本,然后存储到另一个文件中

<强>命令1 (Get-Content filename.xml)| ForEach-Object {$_.replace("some_text" replace_text").replace("some_other_text";replace_text")} | Set-Content filename2.xml

.

将另一个文件复制到原始文件中

Command2

复制-项目-路径filename2.xml -目标文件名.xml -PassThru .xml

删除另一个文件

命令3

Remove-Item filename2.xml

对我来说,为了确保不改变编码(从UTF-8),保持重音…唯一的方法是在之前和之后提到默认编码:

powershell -Command "(gc 'My file.sql' -encoding "Default") -replace 'String 1', 'String 2' | Out-File -encoding "Default" 'My file.sql'"