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


当前回答

Powershell命令-

获取文件的内容,并将其替换为其他文本,然后存储到另一个文件中

命令1 | ForEach-Object {$_.replace("some_text","replace_text").replace("some_other_text","replace_text")} | Set-Content filename2.xml

将另一个文件复制到原始文件中

Command2

复制-项目-路径filename2.xml -目标文件名.xml -PassThru .xml

删除另一个文件

命令3

Remove-Item filename2.xml

其他回答

我不认为有任何内置命令可以做到这一点。我建议你下载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

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

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

我知道我迟到了。

就我个人而言,我喜欢以下的解决方案: ——http://www.dostips.com/DtTipsStringManipulation.php Snippets.Replace

我们还广泛使用重复数据删除功能,帮助我们每天通过SMTP发送大约500封电子邮件: ——https://groups.google.com/forum/ # ! / alt.msdos.batch.nt / sj8IUhMOq6o话题

这些都是本地工作,不需要额外的工具或实用程序。

替代者:

DEL New.txt
setLocal EnableDelayedExpansion
For /f "tokens=* delims= " %%a in (OLD.txt) do (
Set str=%%a
set str=!str:FOO=BAR!
echo !str!>>New.txt
)
ENDLOCAL

DEDUPLICATOR(注意使用-9作为ABA编号):

REM DE-DUPLICATE THE Mapping.txt FILE
REM THE DE-DUPLICATED FILE IS STORED AS new.txt

set MapFile=Mapping.txt
set ReplaceFile=New.txt

del %ReplaceFile%
::DelDupeText.bat
rem https://groups.google.com/forum/#!topic/alt.msdos.batch.nt/sj8IUhMOq6o
setLocal EnableDelayedExpansion
for /f "tokens=1,2 delims=," %%a in (%MapFile%) do (
set str=%%a
rem Ref: http://www.dostips.com/DtTipsStringManipulation.php#Snippets.RightString
set str=!str:~-9!
set str2=%%a
set str3=%%a,%%b

find /i ^"!str!^" %MapFile%
find /i ^"!str!^" %ReplaceFile%
if errorlevel 1 echo !str3!>>%ReplaceFile%
)
ENDLOCAL

谢谢!