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


当前回答

使用FNR

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

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

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

使用的例子: fnr——cl——dir "<目录路径>"——fileMask "hibernate。*"——useRegEx——find "find_str_expression"——replace "replace_string"

其他回答

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

您最好的选择:sed

下面是我在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

替换后的。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

用replace .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"

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

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

创建文件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替换。vbs "C:\Scripts\Text.txt" "Jim " "James "