batch - order and rename files in a directory - batch-file

I've looked around, and there are a lot of posts very similar to this but I can't seem to find an answer that will work for what I need.
I have a big list of files with different extensions that I want to rename to numbers. For example
SomeFileName1.jpg
SomeFileName2.gif
SomeFileName3.mkv
changed to:
1.jpg
2.gif
3.mkv
I want to keep the extensions the same. Only the name should change to 1,2,3 etc.
A while ago I found some code that renamed all the files (don't have the code anymore), but it renamed them in the wrong order. "SomeFileName3.mkv" became "1.mkv" instead of "3.mkv" for example. I'm not sure if I need to sort them first somehow? I'm not very good at this kind of thing so I could really use some help. Thanks

use a for loop to process all files. Use dir to sort the files to your needs. Use a counter. Use delayed expansion to make the counter work.
#echo off
setlocal enabledelayedexpansion
set count=0
for /f "delims=" %%a in ('dir /b /on /a-d') do (
set /a count +=1
ECHO ren "%%a" "!count!%%~xa"
)
for more information read for /?, dir /? and set /?
If the output satisfies you, remove the ECHO to arm the ren command.

Related

CMD recursively batch rename files matching a pattern

this is my first Q on here, please forgive my ignorance in case I miss on best practices. I've reviewed prior requests to similar tasks, but couldn't apply their solutions to the situation described below.
This is about a CMD batch script to rename certain files only in a DIR and its SUBDIRs. All files share the same pattern:
FILENAME 0000.png
where 0000 is an arbitrary four digit number. Thanks to prior solutions here, I do have a working code for one DIR, alas, adding /r didn't make it recursive.
Below is a code snippet from my current CMD .bat (Win10 x64), removing /r works fine when renaming files in just one DIR only:
:dir_files_rename
SETLOCAL
SET "Path=G:\to\dir"
SETLOCAL enabledelayedexpansion
for /r %%f in ("%Path%\*.png") do if %%f neq %~nx0 (
set "filename=%%~nf"
echo %filename%
ren "%%f" "!filename:~0,-5!%%~xf"
)
ENDLOCAL enabledelayedexpansion
goto start
I don't have a method to identify and pass on exclusively files matching above pattern, because I can't come up such a method (doh!). Not elegant at all, because my code affects all files, but at least that's a start.
Cheers, BF

Batch script to iterate through directories starting with a specific string

I'm currently having to manually edit the batch file to manually tell it which directory to work on.
The directories it has to crawl will ALWAYS start with "2020-" (at least for this year), and sometimes there will be multiple of them if I miss a day.
(if it's any easier, they will ALWAYS be in this format: "0000-00-00")
Is there a way to edit this to account for that?
I've tried just making the source_directory just "2020*" but I know that's probably not how this works lol, any help or pointer in the right direction would be amazing.
#echo off
pushd %~dp0
SET source_directory=2020-05-03
SET target_directory=%~dp0
for /f %%a IN ('dir "%source_directory%" /b') do (
move %source_directory%\%%a %target_directory%
)
Sorry, I don't use SO too often so I forget how things need to be done.
This is the solution I've come up with. I don't think it's the intuitive way of doing this, but I don't understand batch well enough to do this without nesting loops.
#echo off
pushd %~dp0
SET source_directory=????-??-??
SET target_directory=%~dp0
for /d %%s in (%source_directory%) do (
for /f %%a IN ('dir "%%s" /b') do (
move %%s\%%a %target_directory%
)
)

Rename Multiple Files in a folder using batch script

I have a folder called TEST. Inside there are 30 files.
Example:
DIM1_UPI_20170102.TXT
DIM2_UPI_20170908.TXT
DIM3_UPI_20180101.TXT
...
I have to rename them by removing the date tag
Exapmple:
DIM1_UPI.TXT
DIM2_UPI.TXT
DIM3_UPI.TXT
Can you please help me writing this in batch file?
Assuming your files are all starting with DIM
#echo off
setlocal enabledelayedexpansion
for /f %%i in ('dir "*.TXT" /b /a-d') do (
set "var=%%~ni"
echo ren !var!%%~xi !var:~0,-9!%%~xi
)
Once you can confirm that it does what you want, and ONLY then, remove the echofrom the last line to actually rename the files.
Important Note. If you have files with similar names, but different date entries, this will not work as you think. as Example:
DIM2_UPI_20170910.TXT
DIM2_UPI_20170908.TXT
The names are the same, but dates differ, making each filename Unique. If you rename them, there can be only 1 DIM2_UPI.TXT So as long as you understand this, you will be fine.
Edit: based on Amazon drive question. Note you need to change the directory portion to how you access amazon drive.
#echo off
setlocal enabledelayedexpansion
for /f %%i in ('dir "DIM*" /b /a-d') do (
set "var=%%~ni"
echo ren !var!%%~xi !var:~0,-16!%%~xi
)

Batch rename file with exclamation mark based on folder's name

I have a folder with photos that has more sub-folders which have dates as name.
For instance it is something like C:\Users\Lorem\Desktop\Photos\22-Dec-98\.
And inside each date folder I have photos that have short descriptions, e.g Third morning on site.png, but some may contain exclamation marks (!).
I managed, by looking at other questions, to come up with a program that adds the date in front of each short description, e.g. 18-Jun-98-Weekend campfire.png, which is what I wanted, but it fails to do so when the short description has an exclamation mark.
#echo OFF
SET /P folderPath="Enter full path of the folder which has the files you want to rename: "
PAUSE
SETLOCAL EnableDelayedExpansion
PAUSE
FOR /F "tokens=*" %%G IN ('dir /b %folderPath%') DO (call :subroutine "%%G")
PAUSE
:subroutine
set date=%1
set date=%date:~1,-1%
set newPath=%folderPath%\%date%\
FOR /F "tokens=*" %%F IN ('dir /b %folderPath%\%1\') DO (call :rename "%%F")
:rename
set fileName=%1
set fileName=%fileName:~1,-1%
set name=%date%-%fileName%
set noname=%newPath%%date%
REN "%noname%" "%name%"
I know the approach that requires input of the folder location is probably not the best option but it was the best workaround I could come up with. All in all, what should I change in/add to my code for it to rename files that contain exclamation marks as well? I would highly appreciate explanations to any changes, if possible, since I am not all that knowledgeable about batch scripting; I only adapted code from different questions/answers. Also I really fail to completely understand what %1 and %%F mean or hold as values so any link to tutorials/short explanation are welcome.
Thanks in advance!

Windows batch file: get last folder name from path

I'm trying to rename .jpg files which is in one of many subdirectories of e:\study\pubpmc\test\extracted.
I want to rename files to LastFolderName_ImageName.jpg.
(For example if Figure1.jpg is in e:\study\pubpmc\test\extracted\folder1
I want it to be renamed like this: folder1_Figure1.jpg)
So I need to take out the last folder name from the file's path.
Since it's my first time with batch scripting, I'm having a hard time.
I googled and made code similar to it
but it doesn't seem to work out.
Can you help me with it and tell me where I've done wrong?
Thank you! :)
#echo off
cd /D "e:\study\pubpmc\test\extracted"
for /r %%f in (*.jpg) do (
set mydir=%%~dpf
set mydir=%mydir:\=;%
for /f "tokens=* delims=;" %%i in (%mydir%) do call :LAST_FOLDER %%i
goto :EOF
:LAST_FOLDER
if "%1"=="" (
#echo %LAST%
goto :EOF
)
set LAST=%1
SHIFT
goto :LAST_FOLDER
)
JosefZ explains the obvious problems with your code, but he failed to point out a subtle problem, though his code fixed it:
FOR /R (as well as the simple FOR) begin iterating immediately, before it has finished scanning the disk drive. It is possible for the loop to reiterate the already named file! This would cause it to be renamed twice, giving the wrong result. The solution is to use FOR /F with command 'DIR /B', because FOR /F always processes the command to completion before iterating.
JosefZ also provides code that works for most situations. But there is a much simpler solution that works always:
#echo off
for /f "delims=" %%A in (
'dir /b /s /a-d "e:\study\pubpmc\test\extracted\*.jpg"'
) do for %%B in ("%%A\..") do ren "%%A" "%%~nxB_%%~nxA"
The "%%A\.." treats the file name as a folder and walks up to the parent folder. So %%~nxB gives the name of the parent folder.
The command could be run as a long one liner, directly from the command line (no batch):
for /f "delims=" %A in ('dir /b /s /a-d "e:\study\pubpmc\test\extracted\*.jpg"') do #for %B in ("%A\..") do #ren "%A" "%~nxB_%~nxA"
Avoid using :label and :: label-like comment inside (command block in parentheses). Using any of them within parentheses - including FOR and IF commands - will break their context.
Using variables inside (command block in parentheses). Read EnableDelayedExpansion: Delayed Expansion will cause variables to be expanded at execution time rather than at parse time [and CLI parses all the (command block in parentheses) at once]
Next script should work for you. Note rename statement is merely echoed for debugging purposes.
#ECHO OFF >NUL
SETLOCAL enableextensions disabledelayedexpansion
set "fromFolder=e:\study\pubpmc\test\extracted"
rem my debug setting set "fromFolder=D:\path"
for /F "tokens=*" %%f in ('dir /B /S /A:D "%fromFolder%\*.*"') do (
set "mydir=%%~ff"
set "last=%%~nxf"
call :renameJPG
)
#ENDLOCAL
goto :eof
:renameJPG
rem echo "%mydir%" "%last%"
for /f "tokens=*" %%i in ('dir /B /A:-D "%mydir%\*.jpg" 2^>nul') do (
echo ren "%mydir%\%%~nxi" "%last%_%%~nxi"
)
goto :eof
Resources:
SETLOCAL, disableDelayedExpansion, ENDLOCAL etc.
An A-Z Index of the Windows CMD command line
Windows CMD Shell Command Line Syntax
I already wrote a function for that. You give it any path and it returns you only it's filename or pathname. Works for any path: Url, Windows path, Linux path, etc...
Copy this function at the end of your batch script: (Instructions below)
rem ===========================================================================
:Name_From_Path
SetLocal
set _TMP_FOLDERNAME=%1
for %%g in ("%_TMP_FOLDERNAME%") do set _TMP_FOLDERNAME=%%~nxg
EndLocal & set _Name_From_Path=%_TMP_FOLDERNAME%
goto :EOF
rem ===========================================================================
Usage:
CALL :Name_Of_Path e:\study\pubpmc\test\extracted\folder1
ECHO %_Name_From_Path%
Result: folder1
If your program or com file traverses these folders when renaming, then it should be able to get the present working directory ( path ), pwd. You may be able to chop everything but the LAST_FOLDER out of this by also creating a PREVIOUS_FOLDER and doing a string replacement.
Or you may be able to break the folder names at the '\' token from the pwd into an array and use a -1 array reference to get the last folder name.
In any circumstance you'll want to check for a present working directory command.
If your creating a large text list of all these and issuing a single call to the batch file.
Then you may be better off with something like:
(Symmantic code warning )
(copy) /folderbase/some_folder/oneormore1/image_from_oneormore1.jpg (to) /folderbase/some_folder/oneormore1/oneormore1_image_from_oneormore1.jpg
Instead of copy, window uses rename, linux uses mv.
The latter example would require simply creating a duplicate list and replacing the \ with a _ while parsing through the tokens.
The code you've given is difficult to make sense of, so its hard to discern if you can simple concatenate the current folder and image name (stringify) and then write or rename them where they are.

Resources