0

Similar to this: Iterate all files in a directory using a 'for' loop but insted I need to iterate over every 5th file within the directory? Whats the most clever way to do it? (doesn't need to be a for loop)

Community
  • 1
  • 1
flor1an
  • 960
  • 3
  • 15
  • 33
  • 2
    add a counter and do only every 5 iterations – phuclv May 13 '17 at 13:44
  • thx but I would prefer using just one line and not a 'complex' if statment – flor1an May 13 '17 at 14:01
  • 1
    You're not going to get a "simple" solution to this. That would require built-in functionality of either `for` or `dir` to be able to do this, and neither one can because that would require doing things to "every few files" to be a normal thing that people do. It's not. Use the counter variable. – SomethingDark May 13 '17 at 14:39

2 Answers2

5

A one liner

set x=0 & for %a in (*) do @((>nul 2>nul set /a "x=(x+1)%5,1/x") || echo %a)

It will

  • Initialize a counter (set x=0)

  • For each file in the folder (for %a in (*) do)

  • Hiding the output of the calc and any error (>nul 2>nul), increase the counter and get the remainder of the value divided by 5 (set /a x=(x+1)%5). This will set the value of the counter to 1 for the first file, 2 for the second, ... and 0 for the fifth file ( 5/5 = 1 with a reminder of 0)

  • Inside the same set /a we also try to calculate 1/x. This will fail with an error (hiden, the reason for the 2>nul) when x=0 (fifth file)

  • The conditional operator || (execute next command when the previous fails) executes the echo %a when the previous 1/x fails

MC ND
  • 69,615
  • 8
  • 84
  • 126
1

I can't understand why everyone wants a one-liner to solve a complex task. But anyhow, here you are:

cmd /v:on /c "@for /f "tokens=1,* delims=[]" %a in ('dir /b /a-d^|find /n /v ""') do @set /a "x=%a %5">nul&@if !x!==0 @echo %a: %b"
Stephan
  • 53,940
  • 10
  • 58
  • 91
  • thx sorry I expressed myself wrongly. I hoped there is a way to add an step variable (or s.th. like this) therfore I was looking for a "one liner". I didn't thought that it is not that easy. But your code works perfectly fine. So much appreciation for it. – flor1an May 13 '17 at 14:49