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


当前回答

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

其他回答

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

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

对我来说,为了确保不改变编码(从UTF-8),保持重音…唯一的方法是在之前和之后提到默认编码:

powershell -Command "(gc 'My file.sql' -encoding "Default") -replace 'String 1', 'String 2' | Out-File -encoding "Default" 'My file.sql'"

dostips.com上的BatchSubstitute.bat是一个使用纯批处理文件进行搜索和替换的示例。

它使用FOR、FIND和CALL SET的组合。

包含“&<>]|^”字符的行可能会被错误处理。


创建文件replace.vbs:

Const ForReading = 1    
Const ForWriting = 2

strFileName = Wscript.Arguments(0)
strOldText = Wscript.Arguments(1)
strNewText = Wscript.Arguments(2)

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFileName, ForReading)
strText = objFile.ReadAll
objFile.Close

strNewText = Replace(strText, strOldText, strNewText)
Set objFile = objFSO.OpenTextFile(strFileName, ForWriting)
objFile.Write strNewText  'WriteLine adds extra CR/LF
objFile.Close

要使用这个修改后的脚本(我们称之为replace.vbs),只需在命令提示符中键入类似于下面的命令:

cscript替换。vbs "C:\Scripts\Text.txt" "Jim " "James "

这是批处理脚本做得不好的一点。

更多辣椒链接到的脚本可以用于某些文件,但不幸的是,它会阻塞那些包含管道和&号等字符的文件。

VBScript是一个更好的内置工具。请看这篇文章的例子: http://www.microsoft.com/technet/scriptcenter/resources/qanda/feb05/hey0208.mspx