我正在使用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
其他回答
下载Cygwin(免费)并在Windows命令行中使用类unix命令。
您最好的选择:sed
这是批处理脚本做得不好的一点。
更多辣椒链接到的脚本可以用于某些文件,但不幸的是,它会阻塞那些包含管道和&号等字符的文件。
VBScript是一个更好的内置工具。请看这篇文章的例子: http://www.microsoft.com/technet/scriptcenter/resources/qanda/feb05/hey0208.mspx
对我来说,为了确保不改变编码(从UTF-8),保持重音…唯一的方法是在之前和之后提到默认编码:
powershell -Command "(gc 'My file.sql' -encoding "Default") -replace 'String 1', 'String 2' | Out-File -encoding "Default" 'My file.sql'"
刚刚使用的FART(“查找和替换文本”命令行实用程序): 优秀的小免费软件的文本替换在一个大的文件集。
安装文件在SourceForge上。
使用的例子:
fart.exe -p -r -c -- C:\tools\perl-5.8.9\* @@APP_DIR@@ C:\tools
将在这个Perl发行版的文件中预览递归执行的替换。
唯一的问题是:屁的网站图标不是很有品位,精致或优雅;)
2017年更新(7年后)jagb在2011年Mikail Tunç的文章“放屁的简单方法-查找和替换文本”的评论中指出
正如Joe Jobs在评论(2020年12月)中指出的,例如,如果你想替换&A,你需要使用引号,以确保&不会被shell解释:
fart in.txt "&A" "B"
下面是我在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
推荐文章
- 用Windows任务调度器运行批处理文件
- GIT克隆在windows中跨本地文件系统回购
- 如何合并2 JSON对象从2个文件使用jq?
- 如何运行一个PowerShell脚本而不显示窗口?
- PowerShell:仅为单个命令设置环境变量
- 为什么这个Windows批处理文件只执行第一行,而在命令shell中执行所有三行?
- 如何将文件内容读入批处理文件中的变量?
- 如何触发命令行PHP脚本的XDebug分析器?
- 环境变量存储在Windows注册表的哪里?
- 有一个好的Valgrind Windows的替代品吗?
- Maven命令行如何指向特定的settings.xml为单个命令?
- Windows和Linux上的c++编译:ifdef开关
- 如何验证批处理文件中是否存在一个文件?
- 如何循环通过文件匹配通配符在批处理文件
- 异步运行Windows批处理文件命令