0

Hi guys I'm new to batch and have a question for my .bat to rename files.

I looked at the following solution and tried to transfer this to my problem: Renaming file names with a BAT file

So my .bat looks like this one:

setlocal enabledelayedexpansion
set /a count=1
set padded_count=000!count!
for /f "tokens=*" %%a in ('dir /b /od *.txt') do (
    ren "%%a" !padded_count!.txt
    set /a count+=1
)

And I have a file with random names for .txt data. E.g.

abc.txt
def.txt
123.txt
456.txt

And I want to change these into:

0001.txt
0002.txt
...

But when I use my .bat its just the first .txt which changes its name. Can you explain me why? And what should I do to get all of these.

Or is it possible to handle this problem with REN in cmd with something like "ren *.txt ___"

41 72 6c
  • 1,600
  • 5
  • 19
  • 30

2 Answers2

2
setlocal enabledelayedexpansion
set /a count=10001
for /f "tokens=*" %%a in ('dir /b /od *.txt') do (
    ren "%%a" !count:-4!.txt
    set /a count+=1
)

where !count:-4! selects the final 4 characters of count.

Magoo
  • 77,302
  • 8
  • 62
  • 84
1

After your comment on the requirement, This is similar to @Magoo's answer, but I am not limiting it to 4 chars.

@echo off
setlocal enabledelayedexpansion
set count=10000
for /f "tokens=*" %%a in ('dir /b /od *.txt') do (
    if "!count:~1!" == "9999" set count=100000
    set /a count+=1
    echo ren "%%a" !count:~1!.txt
)

In this instance, once we get to 9999 we set a new count variable so out files will continue with an additional digit.

ren "file9999.txt" 9999.txt
ren "file10000.txt" 00001.txt
ren "file10001.txt" 00002.txt
...
Gerhard
  • 22,678
  • 7
  • 27
  • 43
  • 1
    Hi Gerhard, now I understand. It works fine, thank you so much for your detailed answer. – 41 72 6c May 09 '19 at 09:19
  • I see that there is a problem with that solution maybe it was not clear from my side. When I have >10 .txt data sets, I expect 0010 instead of 00010 (which is currently the case). Maybe I should combine it with Magoo's solution. – 41 72 6c May 09 '19 at 09:35