我正在使用Windows命令行环境编写批处理文件脚本,并希望将文件(例如“ FOO”)中的某些文本每次更改为另一个文件(例如“ BAR”)。最简单的方法是什么?有内置功能吗?
echo(%text:%search%=%replace%%)
我正在使用Windows命令行环境编写批处理文件脚本,并希望将文件(例如“ FOO”)中的某些文本每次更改为另一个文件(例如“ BAR”)。最简单的方法是什么?有内置功能吗?
echo(%text:%search%=%replace%%)
Answers:
这里的许多答案都帮助我指出了正确的方向,但是没有一个适合我,因此我发布了解决方案。
我有Windows 7,它内置了PowerShell。这是我用来查找/替换文件中所有文本实例的脚本:
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
(命令的gc
缩写Get-Content
)的内容-replace 'foo', 'bar'
只需运行replace命令替换foo
为bar
| Out-File myFile.txt
将输出通过管道传输到文件 myFile.txt
-encoding ASCII
注释指出,可以防止将输出文件转录为unicodePowershell.exe应该已经是PATH语句的一部分,但是如果没有,则可以添加它。它在我的机器上的位置是C:\WINDOWS\system32\WindowsPowerShell\v1.0
-encoding ASCII
或UTF8
或任何需要的方式手动指定编码。还要注意,如果您以UTF8为目标,它可能会在文件的开头引入一个字节顺序标记,而该字节顺序标记不会出现在原始文件中。
-encoding ASCII
。对于将来需要它的任何人,它将是Out-File -encoding ASCII myFile.txt
Set-Content
而不是Out-File
。
如果您使用的是支持.Net 2.0的Windows版本,那么我将替换您的Shell。 PowerShell从命令行为您提供了.Net的全部功能。也有许多内置的命令行开关。下面的示例将解决您的问题。我使用的是命令的全名,别名较短,但这为Google提供了一些便利。
(Get-Content test.txt) | ForEach-Object { $_ -replace "foo", "bar" } | Set-Content test2.txt
powershell -Command "(gc myFile.txt) -replace 'foo', 'bar' | sc myFile.txt"
刚使用过的FART(“ F ind A nd - [R E放置Ť EXT”命令行实用程序):
优良小免费软件为一大组文件中的文本替换。
设置文件在SourceForge上。
用法示例:
fart.exe -p -r -c -- C:\tools\perl-5.8.9\* @@APP_DIR@@ C:\tools
将在此Perl发行版的文件中预览替换内容以进行递归操作。
唯一的问题:FART网站的图标并不完全是高雅,精致或优雅的;)
更新2017年(7年后)jagb指出在评论到2011年的文章“ 放屁的简易方法-查找和替换文本 ”,从MikailTunç
/
,并'
因为这是不工作对我们所有人来说,对我来说,在一些工作情况下,但是它在某些文件上不起作用,我也不知道为什么。.我用它用其他文本替换了文本,以及/
替换-使用字符串替换替换子字符串描述:要将字符串替换为另一个字符串,请使用字符串替换功能。此处显示的示例将字符串变量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
参考:http : //www.dostips.com/DtTipsStringManipulation.php#Snippets.Replace
创建文件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 "
RegExp
。您可以使用它来替换正则表达式:With (New RegExp): strNewText = .Replace(strText, strOldText, strNewText): End With
。您可以使用$1
,$2
... 获取前9个捕获组的文本$9
。
BatchSubstitute.bat
dostips.com上的示例是使用纯批处理文件进行搜索和替换的示例。
它采用的组合FOR
,FIND
和CALL SET
。
其中包含字符的行"&<>]|^
可能会被错误地处理。
注意 -请确保在此答案的末尾看到更新,以获取指向取代REPL.BAT的高级JREPL.BAT的链接
。JREPL.BAT 7.0及更高版本通过该/UTF
选件以及任何其他本机支持Unicode(UTF-16LE)其他字符集(包括UTF-8),通过ADO !!!!
我已经编写了一个名为REPL.BAT的小型混合JScript /批处理实用程序,通过命令行或批处理文件修改ASCII(或扩展ASCII)文件非常方便。纯本地脚本不需要安装任何第三方可执行文件,并且可以在XP及以后的任何现代Windows版本上使用。它也非常快,特别是与纯批处理解决方案相比。
REPL.BAT只需读取stdin,执行JScript regex搜索和替换,然后将结果写入stdout。
这是一个简单的示例,说明如何将test.txt中的foo替换为foo,假设REPL.BAT位于当前文件夹中,或者更好的是位于PATH中的某个位置:
type test.txt|repl "foo" "bar" >test.txt.new
move /y test.txt.new test.txt
JScript regex功能使其功能非常强大,尤其是替换文本能够引用搜索文本中捕获的子字符串的功能。
我在实用程序中包含了许多选项,这些选项使其功能非常强大。例如,结合使用M
和X
选项,可以修改二进制文件!在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的所有相同功能,并且还有更多功能:
与往常一样,完整文档嵌入在脚本中。
原始的简单解决方案现在更加简单:
jrepl "foo" "bar" /f test.txt /o -
JREPL.BAT的当前版本在DosTips上可用。阅读该线程中的所有后续文章,以查看用法示例和开发历史。
\q
表示"
,并且当L和X选项组合在一起时,搜索文字现在支持所有扩展的转义序列。
使用该fnr
实用程序。相对于fart
:
在此处下载FNR:http://findandreplace.io/? z = codeplex
用法示例:
fnr --cl --dir "<Directory Path>" --fileMask "hibernate.*" --useRegEx --find "find_str_expression" --replace "replace_string"
sed -i -b -e 's/FOO/BAR/g' `find . -name *.txt`
-i-就地编辑文件;-b-不处理CR +
我知道我晚会晚了..
就个人而言,我喜欢以下解决方案:- -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(请注意,对于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
谢谢!
在Windows上使用Git时,只需启动git-bash
并使用sed
。或者,在使用Windows 10时(从Linux子系统)启动“ Windows上的Ubuntu上的Bash”并使用sed
。
它是一个流编辑器,但可以使用以下命令直接编辑文件:
sed -i -e 's/foo/bar/g' filename
-i
选项用于在文件名上进行就地编辑。-e
选项表示要运行的命令。
s
用于将找到的表达式“ foo”替换为“ bar”,g
并用于替换找到的所有匹配项。由ereOn注意:
如果您只想替换Git存储库的版本化文件中的字符串,则可能要使用:
git ls-files <eventual subfolders & filters> | xargs sed -i -e 's/foo/bar/g'
哪个奇迹。
git ls-files <eventual subfolders & filters> | xargs sed -i -e 's/foo/bar/g'
它可以创造奇迹。
我在这里尝试了一些现有的答案,并且更喜欢改进的解决方案...
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个字符的行都被换行。真痛苦
使用 replacer.bat
1)使用e?
选项将评估特殊字符序列,例如\n\r
unicode序列。在这种情况下,将替换引号"Foo"
和"Bar"
:
call replacer.bat "e?C:\content.txt" "\u0022Foo\u0022" "\u0022Bar\u0022"
2)在没有引用Foo
和的地方直接替换Bar
。
call replacer.bat "C:\content.txt" "Foo" "Bar"
这是我在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
看看是否有cmd.exe的sed类实用程序在Windows下要求等效的sed,也应适用于此问题。执行摘要:
search and replace
Stack Overflow成员已编写了两个提供功能的批处理文件,dbenham
并在Windows中aacini
使用native built-in jscript
。
他们都是robust
和very swift with large files
比普通批量脚本,也simpler
可用于基本替换文本的。它们都有Windows regular expression
模式匹配。
该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"
该grep-like
帮助程序批处理文件称为findrepl.bat
(由aacini命名)。
正则表达式处于活动状态的示例:
echo This is FOO here|findrepl "FOO" "BAR"
echo and with a file:
type "file.txt" |findrepl "FOO" "BAR" >"newfile.txt"
两者都成为功能强大的系统级实用程序 when placed in a folder that is on the path
,或者可以与批处理文件在同一文件夹中使用,也可以从cmd提示符下使用。
它们都具有case-insensitive
开关以及许多其他功能。
Power Shell命令的运作就像一个魅力
(
test.txt | ForEach-Object { $_ -replace "foo", "bar" } | Set-Content test2.txt
)
刚刚遇到了类似的问题-“在文件内搜索和替换文本”,但是对于文件名和搜索/重复这两个例外,我都需要使用正则表达式。因为我不熟悉Powershell,并且想保存搜索以备后用,所以我需要一些“用户友好”的东西(如果具有GUI,则更可取)。
因此,在谷歌搜索时:)我发现了一个很棒的工具-FAR (查找和替换)(不是FART)。
这个小程序具有不错的GUI并支持正则表达式,用于在文件名和文件内搜索。唯一的缺点是,如果要保存设置,则必须以管理员身份运行程序(至少在Win7上)。
我更喜欢sed
从GNU实用程序中使用Win32,需要注意以下几点
- 单引号
''
在Windows中不起作用,请""
改用sed -i
在Windows中无法使用,需要交换文件
因此,sed
在Windows中查找和替换文件中的文本的工作代码如下
sed -e "s/foo/bar/g" test.txt > tmp.txt && mv tmp.txt test.txt
-i
!就地编辑。如果您的sed版本支持,请从以下答案中检查命令:stackoverflow.com/a/33762001/2492801。
这是批处理脚本不能很好完成的一件事。
链接到morechilli的脚本可用于某些文件,但不幸的是,它将阻塞包含字符(例如竖线和&符)的文件。
VBScript是用于此任务的更好的内置工具。有关示例,请参见本文:http : //www.microsoft.com/technet/scriptcenter/resources/qanda/feb05/hey0208.mspx
@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%"
在.bat中使用Powershell-适用于Windows 7+
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"
下载Cygwin(免费)并在Windows命令行中使用类似Unix的命令。
最好的选择:sed
也可以在https://zoomicon.github.io/tranXform/上查看Replace和ReplaceFilter工具。(包括源)上。第二个是过滤器。
替换文件中字符串的工具位于VBScript中(需要Windows脚本宿主[WSH]在旧的Windows版本中运行)
除非您使用最新的Delphi(或FreePascal / Lazarus)重新编译,否则该过滤器可能不适用于Unicode。
在Visual C ++下进行编码时,我已经多次遇到此问题。如果有,则可以使用Visual Studio查找和替换实用程序。它允许您选择一个文件夹,并将该文件夹中任何文件的内容替换为所需的任何其他文本。
在Visual Studio中:编辑->查找和替换在打开的对话框中,选择文件夹,然后填写“查找内容”和“替换为”框。希望这会有所帮助。