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


当前回答

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

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

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


其他回答

下面是我在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—使用字符串替换替换子字符串 描述:使用字符串替换特性将子字符串替换为另一个字符串。这里显示的示例将字符串变量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

我不认为有任何内置命令可以做到这一点。我建议你下载Gnuwin32或UnxUtils,并使用sed命令(或只下载sed):

sed -c s/FOO/BAR/g filename

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

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

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

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

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