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


当前回答

下载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

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

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

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


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

您最好的选择:sed

在Visual c++下编写代码时,我曾多次遇到过这个问题。 如果你有它,你可以使用Visual studio查找和替换实用程序。它允许您选择一个文件夹,并用您想要的任何其他文本替换该文件夹中任何文件的内容。

在Visual Studio下: 编辑->查找和替换 在打开的对话框中,选择文件夹并填写“查找内容”和“替换为”框。 希望这对你有所帮助。

刚刚遇到了一个类似的问题-“搜索和替换文件中的文本”,但除了文件名和搜索/替换我都需要使用正则表达式。因为我不熟悉Powershell,想要保存我的搜索以供以后使用,所以我需要一些更“用户友好”的东西(如果它有GUI的话更可取)。

所以,在谷歌搜索:)时,我发现了一个很棒的工具——FAR(查找和替换)(不是屁)。

这个小程序有很好的GUI和支持正则表达式在文件名和文件内搜索。唯一的缺点是,如果你想保存你的设置,你必须以管理员身份运行程序(至少在Win7上)。