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

其他回答

用replace .bat

1)用e?选项,将计算特殊字符序列,如\n\r和unicode序列。在这种情况下,将替换引用的“Foo”和“Bar”:

call replacer.bat "e?C:\content.txt" "\u0022Foo\u0022" "\u0022Bar\u0022"

2)直接替换没有引用的Foo和Bar。

call replacer.bat "C:\content.txt" "Foo" "Bar"

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

您最好的选择:sed

我用过perl,它的效果非常好。

perl -pi.orig -e "s/<textToReplace>/<textToReplaceWith>/g;" <fileName>

. trans是它将附加到原始文件的扩展名

对于许多匹配的文件,如*.html

for %x in (<filePattern>) do perl -pi.orig -e "s/<textToReplace>/<textToReplaceWith>/g;" %x

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

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