0

A little bit of a background of what I'm trying to fix. We have files that are created daily that get dumped in a folder that's created for the current day. Some of these files get created with a 0 in front of them. So, 0123456, for example. I'm trying to come up with a batch script that removes the 0 from those files. I came up with this:

@echo off

ECHO Checking HNS for Pics that start with a "0"

For /R "D:\Shared\Quality Photos\TEST2\TEST\" %%a in (0*.*) do ren "%%a" " *.*"

It removes the 0 but replaces it with a space. So, I add this line to the code and it errors out:

For /R "D:\Shared\Quality Photos\TEST2\TEST\" %%a in ( *.*) do ren "%%a" %%a

Thoughts on how to resolve this?

Ruben
  • 199
  • 2
  • 17
CliffB
  • 3
  • 1

2 Answers2

1
@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
FOR /r "%sourcedir%" %%a IN (0*.*) DO (
 SET num=%%~na
 CALL ECHO(REN "%%a" "%%num:~1%%%%~xa"
)

GOTO :EOF

You would need to change the setting of sourcedir to suit your circumstances.

The required REN commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(REN to REN to actually rename the files.

Method : set num to the name part of the file (%%~na) then rename the file, removing the first character and appending the extension (%%~xa)

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

In case you want to remove all leading zeros even if there are more than one, you could try this:

for /F "delims=" %%F in ('
    dir /B /S "D:\Shared\Quality Photos\TEST2\TEST\0*.*"
') do (
    for /F "tokens=* delims=0" %%N in ("%%~nxF") do (
        if not "%%N"=="" ren "%%F" "%%N"
    )
)

The inner for /F loop removes all leading delimiters, namely 0, from the file names.

The if not "%%N"=="" part is only needed in case there could occur files with a base name consisting of zeros only and without a file name extension.


You should not use a for (/R) loop on files which are renamed, copied or (re-)moved within the directory (tree) that is enumerated by the loop, because files might be processed twice or not at all. Refer to this post to learn why. Using for /F and dir /B (/S) is a better alternative as the entire directory (tree) is enumerated before the loop starts to process any items. (In your particular case there would not be a problem since the renamed files do no longer match the pattern, given that there is always a single leading 0 only.)

Community
  • 1
  • 1
aschipfl
  • 33,626
  • 12
  • 54
  • 99