我正在使用Windows命令行环境编写一个批处理文件脚本,并希望更改文件中每次出现的一些文本(例如。“FOO”)和另一个(ex。“酒吧”)。最简单的方法是什么?有内置函数吗?
当前回答
创建文件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 "
其他回答
我在这里摆弄了一些现有的答案,更喜欢我改进的解决方案……
type test.txt | powershell -Command "$input | ForEach-Object { $_ -replace \"foo\", \"bar\" }"
或者如果您想再次将输出保存到文件中…
type test.txt | powershell -Command "$input | ForEach-Object { $_ -replace \"foo\", \"bar\" }" > outputFile.txt
这样做的好处是可以从任何程序输入输出。我们也将研究如何使用正则表达式。不知道如何把它变成一个BAT文件,以便更容易使用…:-(
使用FNR
使用fnr实用程序。它比屁有一些优势:
正则表达式 可选的GUI。有一个“生成命令行按钮”,以创建命令行文本放入批处理文件。 多行模式:GUI允许您轻松地使用多行模式。在《放屁》中,你必须手动转行。 允许您选择文本文件编码。也有一个自动检测选项。
下载FNR: http://findandreplace.io/?z=codeplex
使用的例子: fnr——cl——dir "<目录路径>"——fileMask "hibernate。*"——useRegEx——find "find_str_expression"——replace "replace_string"
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
在Windows上使用Git时,只需启动Git -bash即可 使用sed。或者,当使用Windows 10时,启动“Bash on Ubuntu on Windows”(来自Linux子系统)并使用sed。
它是一个流编辑器,但是可以直接使用以下命令编辑文件:
sed -i -e 's/foo/bar/g' filename
-i选项用于编辑文件名上的位置。 -e option表示要执行的命令。 S用于将找到的表达式“foo”替换为“bar”,g用于替换任何找到的匹配项。
ereOn注:
如果你只想替换Git存储库版本文件中的字符串,你可能想使用:
git ls-files < eventual subfolders & filters > | xargs sed - e, s / foo /酒吧/ g’
这产生了奇迹。
用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"
推荐文章
- 如何从终端/命令行调用VS代码编辑器
- 在Jar文件中运行类
- 我如何找到哪个程序正在使用端口80在Windows?
- 在Windows中有像GREP这样的模式匹配实用程序吗?
- 如何在Windows命令提示符下运行.sh ?
- 如何从命令行通过mysql运行一个查询?
- 如何从命令行在windows中找到mysql数据目录
- 如何从命令行安装cygwin组件?
- 如何更改Git日志日期格式
- 在没有事件源注册的情况下写入Windows应用程序事件日志
- Windows FINDSTR命令的未记录的特性和限制是什么?
- 无法在Windows上从/usr/local/ssl/openssl.cnf加载配置信息
- 使iTerm以与其他操作系统相同的方式翻译“元键”
- 用Windows任务调度器运行批处理文件
- GIT克隆在windows中跨本地文件系统回购