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


当前回答

在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’

这产生了奇迹。

其他回答

我更喜欢使用来自GNU实用程序的sed用于Win32,以下需要注意

单引号“在窗口中不起作用”,请使用“”代替 Sed -i不能在windows中工作,它需要文件交换

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

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

我是Aba搜索和替换的作者,你可以从Windows命令行使用。它可以在没有任何用户交互的情况下进行批量替换,也可以替换多个文件中的文本,而不仅仅是一个文件。

欢迎您试用我的工具;我很乐意回答任何问题。

我用过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

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

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

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