我正在使用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

其他回答

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

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

使用FNR

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

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

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

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

如果你使用的是支持。net 2.0的Windows版本,我会替换掉你的shell。PowerShell从命令行提供了. net的全部功能。还内置了许多命令小程序。下面的例子将解决你的问题。我使用的是命令的全名,还有更短的别名,但这给了你谷歌的一些东西。

(Get-Content test.txt) | ForEach-Object { $_ -replace "foo", "bar" } | Set-Content test2.txt

刚刚使用的FART(“查找和替换文本”命令行实用程序): 优秀的小免费软件的文本替换在一个大的文件集。

安装文件在SourceForge上。

使用的例子:

fart.exe -p -r -c -- C:\tools\perl-5.8.9\* @@APP_DIR@@ C:\tools

将在这个Perl发行版的文件中预览递归执行的替换。

唯一的问题是:屁的网站图标不是很有品位,精致或优雅;)


2017年更新(7年后)jagb在2011年Mikail Tunç的文章“放屁的简单方法-查找和替换文本”的评论中指出


正如Joe Jobs在评论(2020年12月)中指出的,例如,如果你想替换&A,你需要使用引号,以确保&不会被shell解释:

fart in.txt "&A" "B" 

在Windows 7+的。bat中使用powershell

编码utf8是可选的,适合网站

@echo off
set ffile='myfile.txt'
set fold='FOO'
set fnew='BAR'
powershell -Command "(gc %ffile%) -replace %fold%, %fnew% | Out-File %ffile% -encoding utf8"