Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does for /f not ignore blank lines?

I'm trying to get a simple value from a for /f loop in a batch file.

Using the command wmic path win32_localtime get dayofweek gives me the output:

C:\sendemail>wmic path win32_localtime get dayofweek
DayOfWeek
1


C:\sendemail>

So, using the following batch script, I should be able to return a result of "1":

set cmd=wmic path win32_localtime get dayofweek
for /f "tokens=1 skip=1" %%Z in ('%cmd%') do set _myday=%%Z
echo Var is %_myday%

But I don't, it sets the variable at least twice, as seen here :

C:\sendemail>set cmd=wmic path win32_localtime get dayofweek

C:\sendemail>for /F "tokens=1 skip=1" %Z in ('wmic path win32_localtime get dayofweek') do set _myday=%Z

C:\sendemail>set _myday=1

 :\sendemail>set _myday=

C:\sendemail>echo Var is
Var is

C:\sendemail>

At first, I wondered why, then I realised the loop is processing the two blank lines... which it shouldn't be. according to this: http://ss64.com/nt/for_cmd.html

Skip SKIP will skip processing a number of lines from the beginning of the file. SKIP includes empty lines, but after the SKIP is complete, FOR /F ignores (does not iterate) empty lines.

Either, it's not working normally, or those lines are not blank, and are filled with something...

At any rate, how do I get just the day of the week result out of this, and ignore the rest?

like image 222
Stese Avatar asked Jul 09 '15 11:07

Stese


2 Answers

About the lines contents, yes, the output from wmic includes at the end of each line an additional carriage return character that is detected by the for command. That is the reason for your non empty lines.

You can try with

for /f "tokens=2 delims==" %%Z in ('
    wmic path win32_localtime get dayofweek /value
') do for /f %%Y in ("%%Z") do set "_myday=%%Y"

The code is asking wmic to return the information in key=value format and using the equal sign to tokenize the input records. As we request only the second token, for will only process lines that return at least two tokens, lines having a key (first token), an equal sign (delimiter) and a value (second token)

But, the additional carriage return at the end of the line is also included in the value of the variable.

When the variable is used with normal syntax (%_myday%) it is not seen, but with delayed expansion (!_myday!) the additional carriage return will be echoed.

To remove this additional character from the variable, a second for command has been used in the posted code.

like image 98
MC ND Avatar answered Sep 30 '22 19:09

MC ND


This slight midification will work:

@ECHO OFF
set cmd=wmic path win32_localtime get dayofweek
for /f "tokens=1 skip=1" %%Z in ('%cmd%') do (
    set _myday=%%Z
    GOTO BREAK
)
:BREAK
echo Var is %_myday%
PAUSE

Simply jump out of the loop after reading the desired line.

like image 41
MichaelS Avatar answered Sep 30 '22 19:09

MichaelS