What is iterated by this "for /f %%n in ('....') do (...)"

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
alan_b
Expert
Posts: 357
Joined: 04 Oct 2008 09:49

What is iterated by this "for /f %%n in ('....') do (...)"

#1 Post by alan_b » 25 Dec 2011 13:52

Code: Select all

set "file=test.txt"
setlocal EnableDelayedExpansion
<"%file%" (
  for /f %%n in ('type "%file%"^|find /c /v ""') do (
    for /L %%i in (1 1 %%n) do (
      set "LN=" & SET /P "LN="
      ECHO Line %%n is !LN!
   )
  )
)

At first sight I expected the outer %%n "do loop" to iterate through each line in %file%
I now realize that the inner %%i loop has that task.
Does the outer loop only iterate through a wild card set %file%,
or can it initiate any sort of recovery action should SET /P "LN=" reads less lines than the file holds ?
(I have already seen that SET /P reads far too many lines when looking at UNIX text)

Is there any danger in this revision that avoids one level of code indentation
and allows %%j to start its count from 1001 instead of 1
(Sometimes I prefer a fixed 4 digit width count from 1001 through to 9999)

Code: Select all

set "file=test.txt"
setlocal EnableDelayedExpansion
SET BEGIN=1001
<"%file%" (
  for /f %%n in ('type "%file%"^|find /c /v ""') do SET /A LINEND=%BEGIN%+%%n
    for /L %%j in (%BEGIN%, 1, !LINEND!) do (
      set "LN=" & SET /P "LN="
      ECHO Line %%n is !LN!
    )

)


Regards
Alan

aGerman
Expert
Posts: 4738
Joined: 22 Jan 2010 18:01
Location: Germany

Re: What is iterated by this "for /f %%n in ('....') do (...

#2 Post by aGerman » 25 Dec 2011 14:14

Hi Alan,

actually there is no danger in this code. The number of read lines is the same like the number of iterations, the value in %%j doesn't matter. The only thing is that: If your file has more than 998 lines the value in LINEND is >= 2000. I guess you intend to remove the first digit ...

Regards
aGerman

alan_b
Expert
Posts: 357
Joined: 04 Oct 2008 09:49

Re: What is iterated by this "for /f %%n in ('....') do (...

#3 Post by alan_b » 25 Dec 2011 14:46

Thanks for the assurance on safety.

I learnt a long time ago with Command.com to always ensure any count was held to the range 10 to 99, or 100 to 999, or 1000 to 9999, etc.

Often it made no difference but sometimes,
especially on the rare occasions when the code had to be debugged,
I might need to process variables.

Sometimes I had to SORT the output,
and that was painful to look at when the sequence was NOT based numerical value, but went
1,11,12,13,14,15,16,17,18,19,2,21,22,23,24,25,3,4,5,6,7,8,9

Now that I am using CMD.EXE and SET /P the need for debug has risen dramatically.

Hence I now do whatever it takes to ensure that my index values are fixed width and maintain their sequence regardless of any SORT

Regards
Alan

Post Reply