Batch file 批处理脚本:解析文本会产生完全意外的输出,缺少变量值
场景: 我正在尝试重新格式化应用程序的输出(,commandBatch file 批处理脚本:解析文本会产生完全意外的输出,缺少变量值,batch-file,cmd,Batch File,Cmd,场景: 我正在尝试重新格式化应用程序的输出(,commandwpkg.js/query:a)。我仅限于使用标准命令行工具 命令输出由软件包标题及其参数的重复块组成,即: Mozilla Firefox ID: mozilla-firefox Revision: 23.0.1.1 Reboot: false Execute: - Priority: 1
wpkg.js/query:a
)。我仅限于使用标准命令行工具
命令输出由软件包标题及其参数的重复块组成,即:
Mozilla Firefox
ID: mozilla-firefox
Revision: 23.0.1.1
Reboot: false
Execute: -
Priority: 100
Status: Installed
Mozilla Thunderbird
ID: mozilla-thunderbird
Revision: 17.0.8.1
Reboot: false
Execute: -
Priority: 100
Status: Installed
这会产生难以读取的长输出。我也不需要所有的信息
因此,对于每个块,我尝试在一个变量中收集有趣的信息,然后在一行中输出,得到如下结果:
Mozilla Firefox mozilla-firefox 23.0.1.1 Installed
Mozilla Thunderbird mozilla-thunderbird 17.0.8.1 Installed
问题:
为了实现这一点,我首先开始使用以下代码解析输出:
rem Split all lines into two tokens
@for /f "tokens=1,2" %%G IN ('%WPKG_CMD% /query:a') DO @(
rem With first token, check what to do:
rem I can get known strings (Store, Ignore)
rem or I can get package name (NewLine)
@set WpkgListAll_ToDo=NewLine
@if [%%G]==[ID:] set WpkgListAll_ToDo=Store
@if [%%G]==[Revision:] set WpkgListAll_ToDo=Store
@if [%%G]==[Reboot:] set WpkgListAll_ToDo=Ignore
@if [%%G]==[Execute:] set WpkgListAll_ToDo=Ignore
@if [%%G]==[Priority:] set WpkgListAll_ToDo=Ignore
@if [%%G]==[Status:] set WpkgListAll_ToDo=Store
rem Echo for debug purpose
@echo [%%G][%WpkgListAll_ToDo%]
rem Next follows some unimportant code
)
从上面的代码中,我将完全期望得到以下调试输出:
[Mozilla][NewLine]
[Revision:][Store]
[Reboot:][Ignore]
[Execute:][Ignore]
[Priority:][Ignore]
[Status:][Store]
[Mozilla][NewLine]
[ID:][Store]
[Revision:][Store]
[Reboot:][Ignore]
[Execute:][Ignore]
[Priority:][Ignore]
[Status:][Store]
我得到的是…:
[Mozilla][]
[Revision:][]
[Reboot:][]
[Execute:][]
[Priority:][]
[Status:][]
[Mozilla][]
[ID:][]
[Revision:][]
[Reboot:][]
[Execute:][]
[Priority:][]
[Status:][]
…我一直在努力理解为什么,但我失败了
问题:
有人能解释一下为什么输出失败,我应该怎么做才能正确吗?您必须使用延迟变量展开。首先,在脚本的开头添加
setlocalenabledelayedexpansion
行,在脚本的末尾添加endlocal
。然后将echo语句更改为:
@echo [%%G][!WpkgListAll_ToDo!]`
必须使用延迟变量展开。首先,在脚本的开头添加
setlocalenabledelayedexpansion
行,在脚本的末尾添加endlocal
。然后将echo语句更改为:
@echo [%%G][!WpkgListAll_ToDo!]`
已编辑标记-这是Windows批处理文件,不是MS-DOS。MS-DOS不支持FOR/F语法。已编辑的标记-这是Windows批处理文件,而不是MS-DOS。MS-DOS不支持FOR/F语法。已保存我的一天!谢谢我今天过得很愉快!谢谢D