我正在使用Windows命令行环境编写批处理文件脚本,并希望将文件(例如“ FOO”)中的某些文本每次更改为另一个文件(例如“ BAR”)。最简单的方法是什么?有内置功能吗?
这里的许多答案都帮助我指出了正确的方向,但是没有一个适合我,因此我发布了解决方案。
我有Windows 7,它内置了PowerShell。这是我用来查找/替换文件中所有文本实例的脚本:
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
注释指出,可以防止将输出文件转录为unicodePowershell.exe应该已经是PATH语句的一部分,但是如果没有,则可以添加它。它在我的机器上的位置是C:\WINDOWS\system32\WindowsPowerShell\v1.0
更新
显然,现代Windows系统内置了PowerShell,可让您直接使用
(Get-Content myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句