Bit of a strange thing is happening to me. I put a renaming batch file together a few years ago (with a lot of help from various places, including StackOverflow) for a project i was working on. It would rename some files and prefix them with the first 5 characters from the parent folder (i.e. '12345 - Site'). I haven't used the BAT file for a good few months and now have a need to, but it is not working correctly.
It is renaming the files, but it is using the whole of the parent folder instead of just the first 5 characters. I have tested it on another PC and run it in folders where it previously worked.
Does anyone have any ideas as to why this would happen, how to fix it, or what I could add to the batch file to achieve the same result?
Just to point out, I am a complete novice and spent many nights getting the first batch file working through trial and error and cutting and pasting from similar batch file requests on the web.
My current code:
for %%z in ("%cd%") do (
for %%a in ("%%~dpz%\.") do (
for /f "delims=" %%i in ('dir /b /a-d *.pdf,*.xlsx,*.docx,*.xlsm') do move "%%i" "%%~nxz %%i"))
This should work for you.
for %%z in ("%cd%") do (
for %%a in ("%%~dpz%\.") do (
for /f "delims=" %%i in ('dir /b /a-d *.pdf,*.xlsx,*.docx,*.xlsm') do call :renameStuff "%%i" "%%~nxz"
)
)
goto :eof
:renameStuff
set "originalName=%~1"
set "parentFolder=%~2"
echo move "%originalName%" "%parentFolder:~0,5% %originalName%"
exit /b
The specific bit you're looking for is %parentFolder:~0,5%
, which takes a substring of %parentFolder% starting at character 0 and stopping after 5 characters. This gives you the first 5 characters that you're looking for.
The tricky bit is that you can't use this on those for
loop %%z
type variables. Thus, you have to pass it to another variable. Further, because you've got some nested loops delayed expansion makes this really ugly, so I've passed the variable into a subroutine (call :renameStuff "%%i" "%%~nxz"
) which turns those into %1
and %2
type variables, and then passed it into ordinary variables (set "originalName=%~1"
) that this will work with.