批量跳过WMIC命令输出的最后一个空行 [英] Skipping last empty line of WMIC command output in batch
问题描述
我正在尝试以JSON格式格式化命令的输出:
I am trying to format the output of a command in JSON as such:
echo "patches" : {
set patches="wmic qfe get HotfixID"
for /f "skip=1" %%i in (' %patches% ') do (
set /a count=count+1
call echo "!count!" : "%%i",
)
echo }
一切都很好,直到我打到补丁列表的末尾,它会读取最后一个补丁之后的行,然后打印""
.
Everything is fine until I hit the end of the list of patches where it reads the line after the last patch and then prints ""
.
我应该如何使它停止?
如果可能的话,我想避免使用文本文件.
If possible, I would like to avoid using text files.
推荐答案
在for /f
循环内,放置另一个:
Inside the for /f
loop, place another one:
for /f "skip=1" %%i in ('%patches%') do for /f "delims=" %%j in ("%%i") do (
rem // use `%%j` in the loop body
)
wmic
命令返回Unicode输出.由于for /f
并不适合处理此类问题,因此会产生诸如孤立的回车(CR)之类的伪像,从而导致您遇到的效果(由于for /f %%i
循环中包含此类CR,最后一行并不会显示为空;请记住,for /f
会跳过真正为空的行).在内部放置另一个for /f
循环,然后对每个项目进行重复处理可消除此类伪像.
The wmic
command returns Unicode output. Since for /f
is not perfect for handling such, it produces artefacts like orphaned carriage-returns (CR), leading to the effect you encounter (the last line does not appear empty to your for /f %%i
loop as it contains such a CR; remember that for /f
skips lines that are really empty). Placing another for /f
loop inside and hence double-processing each item removes such artefacts.
这是固定的脚本:
echo "patches" : {
set "patches=wmic qfe get HotfixID"
for /f "skip=1" %%i in ('%patches%') do for /f "delims=" %%j in ("%%i") do (
set /a count=count+1
echo "!count!" : "%%j",
)
echo }
由于我没有得到call
命令的目的,因此我将其删除了.
Since I did not get the purpose of the call
command, I simply removed it.
双重解析方法实际上归功于 dbenham -请参见他对 WMIC和FOR/F:针对尾随< CR>问题.
The double-parsing method is actually credited to dbenham -- see his answer to Why is the FOR /f loop in this batch script evaluating a blank line? and also his external article WMIC and FOR /F : A fix for the trailing <CR> problem.
这篇关于批量跳过WMIC命令输出的最后一个空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!