我正在使用Windows命令行环境编写一个批处理文件脚本,并希望更改文件中每次出现的一些文本(例如。“FOO”)和另一个(ex。“酒吧”)。最简单的方法是什么?有内置函数吗?
当前回答
下面是我在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
其他回答
下载Cygwin(免费)并在Windows命令行中使用类unix命令。
您最好的选择:sed
Replace—使用字符串替换替换子字符串 描述:使用字符串替换特性将子字符串替换为另一个字符串。这里显示的示例将字符串变量str中所有出现的“teh”拼写错误替换为“The”。
set str=teh cat in teh hat
echo.%str%
set str=%str:teh=the%
echo.%str%
脚本输出:
teh cat in teh hat
the cat in the hat
裁判:http://www.dostips.com/DtTipsStringManipulation.php # Snippets.Replace
在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’
这产生了奇迹。
如果你使用的是支持。net 2.0的Windows版本,我会替换掉你的shell。PowerShell从命令行提供了. net的全部功能。还内置了许多命令小程序。下面的例子将解决你的问题。我使用的是命令的全名,还有更短的别名,但这给了你谷歌的一些东西。
(Get-Content test.txt) | ForEach-Object { $_ -replace "foo", "bar" } | Set-Content test2.txt
我用过perl,它的效果非常好。
perl -pi.orig -e "s/<textToReplace>/<textToReplaceWith>/g;" <fileName>
. trans是它将附加到原始文件的扩展名
对于许多匹配的文件,如*.html
for %x in (<filePattern>) do perl -pi.orig -e "s/<textToReplace>/<textToReplaceWith>/g;" %x
推荐文章
- 如何从终端/命令行调用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中跨本地文件系统回购