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


当前回答

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

您最好的选择:sed

其他回答

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

sed -c s/FOO/BAR/g filename

刚刚使用的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" 

这里的很多答案都帮我指明了正确的方向,但是没有一个适合我,所以我把我的解决方案贴出来。

我用的是内置PowerShell的Windows 7。下面是我用来查找/替换文件中所有文本实例的脚本:

powershell -Command "(gc myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt"

解释一下:

powershell会启动Windows 7中包含的powershell.exe - command”…是powershell.exe的命令行参数,其中包含要运行的命令 (gc myFile.txt)读取myFile.txt的内容(gc是Get-Content命令的缩写) -replace 'foo', 'bar'简单地运行replace命令将foo替换为bar | Out-File myFile.txt输出到文件myFile.txt -encoding ASCII防止将输出文件转录为unicode,正如注释所指出的那样

Powershell.exe应该已经是PATH语句的一部分,但如果不是,可以添加它。它在我机器上的位置是C:\WINDOWS\system32\WindowsPowerShell\v1.0

显然,现代的windows系统都内置了PowerShell,允许你直接使用

(Get-Content myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt

我在这里摆弄了一些现有的答案,更喜欢我改进的解决方案……

type test.txt | powershell -Command "$input | ForEach-Object { $_ -replace \"foo\", \"bar\" }"

或者如果您想再次将输出保存到文件中…

type test.txt | powershell -Command "$input | ForEach-Object { $_ -replace \"foo\", \"bar\" }" > outputFile.txt

这样做的好处是可以从任何程序输入输出。我们也将研究如何使用正则表达式。不知道如何把它变成一个BAT文件,以便更容易使用…:-(

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