Skipping last empty line of WMIC command output in batch

前端 未结 2 607
-上瘾入骨i
-上瘾入骨i 2021-01-29 04:57

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%         


        
相关标签:
2条回答
  • 2021-01-29 05:15

    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
    )
    

    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.

    Here is the fixed script:

    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 }
    

    Since I did not get the purpose of the call command, I simply removed it.


    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.

    0 讨论(0)
  • 2021-01-29 05:32

    Skipping last empty line of WMIC command output in batch

    The simplest solution is to use findstr to remove the blank lines:

    for /f "skip=1" %%i in ('%patches% ^| findstr /r /v "^$"')
    

    No extra for loop required.


    Further Reading

    • An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
    • findstr - Search for strings in files.
    0 讨论(0)
提交回复
热议问题