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


当前回答

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

您最好的选择:sed

其他回答

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

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

sed -c s/FOO/BAR/g filename

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

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

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

Power shell命令的工作就像一个魅力

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