我正在使用Windows命令行环境编写一个批处理文件脚本,并希望更改文件中每次出现的一些文本(例如。“FOO”)和另一个(ex。“酒吧”)。最简单的方法是什么?有内置函数吗?
当前回答
Power shell命令的工作就像一个魅力
(
test.txt | ForEach-Object { $_ -replace "foo", "bar" } | Set-Content test2.txt
)
其他回答
我不认为有任何内置命令可以做到这一点。我建议你下载Gnuwin32或UnxUtils,并使用sed命令(或只下载sed):
sed -c s/FOO/BAR/g filename
下面是我在Win XP上发现的一个解决方案。在我运行的批处理文件中,我包括以下内容:
set value=new_value
:: Setup initial configuration
:: I use && as the delimiter in the file because it should not exist, thereby giving me the whole line
::
echo --> Setting configuration and properties.
for /f "tokens=* delims=&&" %%a in (config\config.txt) do (
call replace.bat "%%a" _KEY_ %value% config\temp.txt
)
del config\config.txt
rename config\temp.txt config.txt
替换后的。bat文件如下所示。我没有找到在同一个批处理文件中包含该函数的方法,因为%%a变量似乎总是给出for循环中的最后一个值。
replace.bat:
@echo off
:: This ensures the parameters are resolved prior to the internal variable
::
SetLocal EnableDelayedExpansion
:: Replaces Key Variables
::
:: Parameters:
:: %1 = Line to search for replacement
:: %2 = Key to replace
:: %3 = Value to replace key with
:: %4 = File in which to write the replacement
::
:: Read in line without the surrounding double quotes (use ~)
::
set line=%~1
:: Write line to specified file, replacing key (%2) with value (%3)
::
echo !line:%2=%3! >> %4
:: Restore delayed expansion
::
EndLocal
创建文件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 "
Power shell命令的工作就像一个魅力
(
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'"
推荐文章
- 如何从终端/命令行调用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中跨本地文件系统回购