batch – How to detect blank spaces?

Question:

I have a .bat that is used to change names to .jpg files

The original file name is a 4 or 5 digit numeric code followed by a space and a string of alphanumeric characters. Such that:

1001 ASDFGJHJS.jpg

I have this code that renames them taking the first 5 characters.

for %%i in ("*.jpg") do (set fname=%%i) & call :rename
goto :eof
:rename
::Cuts off  five chars, then appends .jpg
ren "%fname%" "%fname:~0,5%.jpg"
goto :eof

How do I detect the space so that it is the first 4 or 5 digits that I take?

Answer:

The solution I found was something simple that I hadn't tried:

IF "%fname:~4,1%"==" " (ren "%fname%" "%fname:~0,4%.jpg") else (ren "%fname%" "%fname:~0,5%.jpg")

With the IF "%fname:~4,1%"==" " I check the 5th character, if it is a blank space I take the first 4 characters, if it is not a space I take the first 5

Scroll to Top