In the previous article I introduced how to use batch to search and replace text in strings but what can you do with it?
Let's say you have a whole bunch of files that you want to work with but you are using some old program that frustratingly refuses to allow you to open files that have spaces in their names. Luckily this is a rare case now days but I recently came across such circumstances.
You could rename them by hand, but if you have lots of files it could get old fast. Believe me, renaming thousands of files by hand is a pain in the wrists.
The first possibility is that you could delete the spaces such as in the following:
DeleteSpaces.bat
@Echo Off
SetLocal EnableExtensions
@Echo Renaming all files in the folder to remove spaces.
For /f "delims=" %%a In ('dir /a-d /s /b *.*') Do Call :DeleteSpaces "%%~a"
GoTo :EOF
:DeleteSpaces
Set t=%~n1
Call Set t=%%t: =%%
Ren "%~1" "%~dp1%t%%~x1"
GoTo :EOF
But deleting spaces may not be what you want to do, after all you are deleting valuable information that spaces bring. What about replacing the spaces with underscores_ instead?:
UnderscoreSpaces.bat
@Echo Off
SetLocal EnableExtensions
Echo Renaming all files in the folder Replacing spaces with Underscores.
For /f "delims=" %%a In ('dir /a-d /s /b *.*') Do Call :UnderscoreSpaces "%%~a"
GoTo :EOF
:UnderscoreSpaces
Set t=%~n1
Call Set t=%%t: =_%%
Ren "%~1" "%~dp1%t%%~x1"
GoTo :EOF
What these both do is retrieve a list of tiles then use modifications of the find and replace function and replaces spaces either with nothing or an underscore then rename the files accordingly.
One thing I made certain to do is limit the renaming only to the filename and not the rest of the string. This is done by setting "t=%~n1" the n flag pulls only the filename. When the rename is done it is all put back together using "%~dp1%t%%~x1" the flags d and p are drive and path then %t% is the filename and it completes it using the flag x for extension.
note that SetLocal keeps the variables set in either script contained within the scripts so that they don't spill out into other scripts.
No comments:
Post a Comment