Reputation: 739
Heythere. I need your guys help with file renaming using a .bat file. I got multiple files that I need to be cropped after specified character number. For exmample, I want to crop name of the files after their fifth character, this way
filename.exe > filen.exe
anothername.exe > anoth.exe
absolutelydifferentname.exe > absol.exe
And, if possible, I'd like to know how to do the opposite. I mean, leaving the certain # of characters at the end, cropping from the beginning of the filename.
Thank you.
Upvotes: 2
Views: 3465
Reputation: 130919
The Iridium solution will fail if any file name contains the !
character because expansion of %%i
will fail if value contains !
and delayed expansion is enabled. This is easily fixed by toggling delayed expansion on and off within the loop.
The explicit disabling of delayed expansion at the top is normally not needed. But it is possible for delayed expansion to already be enabled at the start of a batch file, so I included it just to be safe.
@echo off
setlocal disableDelayedExpansion
for %%F in ("<Directory name here>\*") do (
set "full=%%F"
set "name=%%~nF"
set "ext=%%~xF"
setlocal enableDelayedExpansion
ren "!full!" "!name:~0,5!!ext!"
endlocal
)
Upvotes: 2
Reputation: 23731
If you want to do it in a batch file, the following should work:
@echo off
setlocal ENABLEDELAYEDEXPANSION
for %%i in (<Directory name here>\*) do (
set filename=%%~ni
ren "%%~i" "!filename:~0,5!%%~xi"
)
endlocal
If you wish to change the number of characters used to construct the final filenames, change the "5" in ren "%%~i" "!filename:~0,5!%%~xi"
.
To take the last 5 characters try: ren "%%~i" "!filename:~-5!%%~xi"
For all except the first 5 characters: ren "%%~i" "!filename:~5!%%~xi"
Upvotes: 4
Reputation: 5137
Just incase this is a once-off, or some other manual scenario, have a look at CKRename
Upvotes: 0