garrison
garrison

Reputation: 11

To batch reduce a space in the file names

After batch rename so many files using a batch file, I found that the naming structure looks like below:

FILENAME__###.jpg

There are two spaces (the two underscores above) between the FILENAME and the numbering ###. How can I remove one space (or reduce that 2 spaces to 1 space) for all of the files (may with different suffixes) under a directory with the above naming structure using a batch command file in the command prompt of Windows system.

Thank you very much.

Upvotes: 0

Views: 324

Answers (1)

dbenham
dbenham

Reputation: 130829

Assuming you haven't any file names that begin with space, then

@echo off
for %%F in ("*  *") do for /f "tokens=1* eol= delims= " %%A in ("%%F") do ren "%%F" "%%A %%B"

The above will handle a single run of any number of consecutive spaces and convert that run into a single space.

If you have multiple runs of spaces, then you can simply parse out more tokens. You don't have to worry about parsing more tokens than exist because Windows automatically trims trailing spaces and dots from file names. It is possible to handle up to 31 space runs (32 tokens) with a single FOR /F, and it is simple to handle 25 space runs (tokens A through Z). The code below handles 9 space runs, which is likely more than enough.

@echo off
for %%f in ("*  *") do for /f "tokens=1-9* eol= delims= " %%A in ("%%f") do ^
ren "%%f" "%%A %%B %%C %%D %%E %%F %%G %%H %%I %%J"

Or if you get a hold of JREN.BAT, a hybrid JScript/batch regular expression renaming utility, then you can use:

jren "  +" " " /fm "*  *"

The JREN.BAT solution will handle all instances of consecutive spaces, no matter how many.

If you use JREN.BAT within another batch script, then you must use call jren so that control returns to your script.

Upvotes: 1

Related Questions