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


当前回答

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

其他回答

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

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

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

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

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

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

VBScript是一个更好的内置工具。请看这篇文章的例子: http://www.microsoft.com/technet/scriptcenter/resources/qanda/feb05/hey0208.mspx

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

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

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


在Windows上使用Git时,只需启动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用于替换任何找到的匹配项。


ereOn注:

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

git ls-files < eventual subfolders & filters > | xargs sed - e, s / foo /酒吧/ g’

这产生了奇迹。