Mass Renaming (Adding Suffix/Prefix) of files recursively in Windows - windows

I have a folder with many sub-folders which have further sub-folders. each folder has a number of files.
I want to rename all the file by adding some suffix to them
for ex:
Original: FileName1.ext
Final : Suf_FileName1.ext
To carry out this function, found this command online
`FOR /R %x IN (*) DO ren "%x" Suf_*`
but this replaces the initial characters in the original file name
like
Original: FileName1.ext
Final : Suf_Name.ext
(please note it has removed initial characters in the initial file name )
Please suggest changes/modifications in the above command,
or another command to carry out the function.
Thanks in Advance.

When you use a for command to iterate over a set of files, the for replaceable parameter (%x in your sample) contains a reference to the file.
When you use %x in the commands contained in the do clause, this parameter is replaced by information of the file being processed, by default the name and extension of the file (when using a simple for) or the file with full path (when using a recursive for /R), but you can decide and changee what information you want to use. The replaceable parameter allows the usage of some modifiers (you can see the full list if you execute for /?)
In your case, for your rename mask you need the name and extension of the file being referenced (I've changed your %x with %F so the syntax is clearer)
%~nxF
^^^^.... replaceable parameter
||+..... extension of the file referenced
|+...... name of the file referenced
+....... operator for modifier usage
Your command could be something like
for /R %F in (*) do echo ren "%F" "Suf_%~nxF"
note: The echo in the command is just a debugging habit. Before changing anything, first show to console the commands that will be executed. If the output seems correct then we only have to remove the echo and run the command again.
Remember that if you want to use the command inside a batch file, you need to escape the percent signs in the for replaceable parameters by doubling them. Inside a batch file the previous command will be
for /R %%F in (*) do echo ren "%%F" "Suf_%%~nxF"

Related

Trying to batch merge 2 .jpeg's horizontally and put them in a different folder after

this is for my doctoral thesis in medicine. So please excuse my noobishnis in programing.
I have a bunch (about 4000 files) of scans from patients. There is a front and a back .jpg for each patient. And there where multiple patients each day.
The folder structure looks like this:
\images
\2017-08-21
\pa_102165.jpg
\pa_10216500001.jpg
\2017-06-14
\pa_101545.jpg
\pa_10154500001.jpg
\pa_104761.jpg
\pa_10476100001.jpg
\pa_107514.jpg
\pa_10751400001.jpg
\2017-03-73
\pa_109631.jpg
\pa_10963100001.jpg
\pa_108624.jpg
\pa_10862400001.jpg
Where in the first example 2017-08-21 is the date the patient came in, pa_102165.jpg is the front and pa_10216500001.jpg is the back. So the front is always pa_10XXXX.jpg and the back is pa_10XXXX00001.jpg. I had no hand in the nameing scheme.
My goal is to make a batchscript that merges the 2 corresponding .jpgs of each patient horizontally and automatically puts them in a different folder, so that I don't have to do it manually with something like MS Paint.
For example like this:
\images
\merged
\2017-08-21
\pa_102165_merged.jpg
\2017-06-14
\pa_101545_merged.jpg
\pa_104761_merged.jpg
\pa_107514_merged.jpg
\2017-03-73
\pa_109631_merged.jpg
\pa_108624_merged.jpg
I'm working on Windows 10 and found two promising methods so far but fail to comprehend how to make this into a batch file or something like it.
IrfanView Thumbnails
1. Mark the 2 corresponding .jpgs
2. File>Create contact sheet from selected files...
3. Create
4. File>Save as... in destination folder which i have to create for every day
which is faster than merging them by hand but would consume multiple workdays to do for all the pairs
and...
ImageMagic in Windows cmd
C:\Users\me\doctor\Images\test\images\2016-03-31>convert pa_102165.jpg pa_10216500001.jpg +append pa_102165_merged.jpg
This produces the merged .jpeg in the same folder the input images are in. This looks more promising but I fail to grasp how I could automate this process given the nameing scheme and the folder structure.
Thanks for taking the time to read this! I'm happy for every input you have!
This should get you fairly close. Essentially it is using the power of the FOR command modifiers to extract the base file name and file extension. The FOR /F command is capturing the output of the DIR command that is piped to the FINDSTR command. We are doing that so we only grab files with the file mask of pa_######.jpg
Once we have that we use the command modifiers with the IF command to make sure the 00001 file exists. If it does exist then it will execute the convert command. For the sake of making sure the code is performing correctly I am just ECHOING the output to the screen. If the output on the screen looks correct then remove the ECHO so that the CONVERT command executes.
#echo off
CD /D "C:\Users\me\doctor\Images\test\images"
FOR /F "delims=" %%G IN ('DIR /A-D /B /S PA_*.jpg ^|findstr /RIC:"pa_[0-9][0-9][0-9][0-9][0-9][0-9]\.jpg$"') DO (
IF EXIST "%%~dpnG00001%%~xG" (
ECHO convert "%%G" "%%~dpnG00001%%~xG" +append "%%~dpnG_merged%%~xG"
)
)
This task could be done with IrfanView with the following batch file stored in the directory containing the folder images.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "IrfanView=%ProgramFiles(x86)%\IrfanView\i_view32.exe"
set "SourcePath=%~dp0images"
set "TargetPath=%~dp0merged"
for /F "delims=" %%I in ('%SystemRoot%\System32\where.exe /R "%SourcePath%" pa_10????.jpg 2^>nul') do for %%J in ("%%~dpI.") do (
if not exist "%TargetPath%\%%~nxJ\%%~nI_merged%%~xI" if exist "%%~dpnI00001%%~xI" (
if not exist "%TargetPath%\%%~nxJ\" md "%TargetPath%\%%~nxJ"
if exist "%TargetPath%\%%~nxJ\" (
echo Merging "%%~nxJ\%%~nxI" and "%%~nxJ\%%~nI00001%%~xI" ...
"%IrfanView%" /convert="%TargetPath%\%%~nxJ\%%~nI_merged%%~xI" /jpgq=95 /panorama=(1,"%%I","%%~dpnI00001%%~xI"^)
)
)
)
endlocal
There must be customized the fully qualified file name of IrfanView in the third line. There can be modified also the percent value of option /jpgq which defines the quality of the output JPEG file.
The command WHERE searches recursive in subdirectory images of the directory containing the batch file for files matching the wildcard pattern pa_10????.jpg with ignoring all other files. The found file names are output with full path and this list of file names is captured by FOR and processed line by line after WHERE finished. WHERE is executed in this case by one more cmd.exe started in background with option /c and the command line within ' as additional arguments and not by cmd.exe processing the batch file.
Read the Microsoft documentation about Using command redirection operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded where command line with using a separate command process started in background.
Each image file with full name (drive + path + name + extension) is assigned one after the other to the loop variable I. For each file name one more FOR loop is used which processes just the full path to the current image file to assign this path with a dot appended to loop variable J. The dot at end means current directory, i.e. the directory containing current image file to process.
There is next checked with the first IF condition if for that image file does not exist already a matching pa_10????_merged.jpg file in which case there is nothing to do for the current image file. That means the batch file can be executed on same folder as often as wanted because of it runs IrfanView only for the source JPEG files for which the appropriate target JPEG file does not exist already.
The second IF condition checks if the back image exists also in the directory of current front image as otherwise nothing can be merged at all.
There is next checked with the third IF condition if the target directory exists already and this directory is created if that is not the case.
The last IF condition checks once again the existence of the target directory and if that exists now as expected, IrfanView is called with the appropriate options to create the merged image file in the target directory with the appropriate file name.
The closing round bracket ) on IrfanView command line must be escaped with ^ to be interpreted literally by cmd.exe to pass this closing parenthesis to IrfanView instead of interpreting it as end of one of the command blocks opened with ( above.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /? ... explains %~dp0 ... drive and path of argument 0 which is the batch file path always ending with a backslash
echo /?
endlocal /?
for /?
if /?
md /?
setlocal /?
where /?
Double click on the text file i_options.txt in program files folder of IrfanView for the description of the IrfanView options as used in the batch file.

Batch script to rename all files with spaces [duplicate]

This question already has answers here:
Variables are not behaving as expected
(1 answer)
Example of delayed expansion in batch file
(5 answers)
At which point does `for` or `for /R` enumerate the directory (tree)?
(1 answer)
Closed 1 year ago.
I'm trying to write a batch script that'll read all the pdf files in a folder and rename them such that there are no spaces in them. So I've typed up the below code. Although most of the parts of the code seems to work in isolation, I get an error when running the code together.
for /r %%f in (*.txt) do (
set filename=%%~nxf
set new=%filename: =%
ren "%filename%" %new%
)
The filename is detected correctly by line2. But on line3, I don't get the value I've stored in line2. Interestingly enough, if I were to run the command again in the same prompt, line3 then works (filename variable is read correctly). It must be how the for loop operates in a batch script. If I run the below code exactly 3 times in the same command prompt, the code works perfectly fine (I assume because all variables are now set correctly). Can someone please help point me in the right direction? Thanks in advance.
Note: I have a filename called "filename .txt" in the working directory, which I realise wasn't the best choice of filename. :|
(error in screenshot)
Open a command prompt, run set /? and read the output help carefully and completely from top of first to bottom of last page, especially the section about delayed expansion explained also by Variables are not behaving as expected. The Windows command processor cmd.exe processes the entire command block starting with ( and ending with matching ) before executing command FOR at all. All environment variables using %...% syntax are expanded (replaced) already during this processing phase by the appropriate variable expansion result.
So executed is the following on environment variable filename not already defined:
for /R %f in (*.txt) do (
set filename=%~nxf
set new= =
ren ""
)
That can be seen on debugging the batch file by running it from within a command prompt window instead of double clicking the batch file. This results in the following error message for each *.txt file found in current directory and all its subdirectories:
The syntax of the command is incorrect.
The syntax of the command ren is of course incorrect.
One solution is using following batch code:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
for /F "delims=" %%I in ('dir "* *.txt" /A-D /B /S 2^>nul') do (
set "FullName=%%I"
set "FileName=%%~nxI"
setlocal EnableDelayedExpansion
ren "!FullName!" "!FileName: =!"
endlocal
)
endlocal
The first two lines define completely the required execution environment for the batch file.
There is not used a for /R loop as that can cause troubles depending on file system of current drive and the file names to modify on renaming the files with file extension .txt while the FOR loop iterates of the file system entries matching the wildcard pattern.
The usage of the for /F loop results in first starting one more command process in background with %ComSpec% /c and the specified command line appended as additional arguments. So with Windows installed in C:\Windows is executed in background:
C:\Windows\System32\cmd.exe /C dir "* *.txt" /A-D /B /S 2>nul
The second command process runs DIR which
searches in current directory and all its subdirectories because of option /S
for just files because of option /A-D (attribute not directory)
of which name matches the wildcard pattern * *.txt in long or short name
and outputs the found file names in bare format because of option /B which means just the file names with full path because of option /S.
The command DIR finds also matching file names of files with hidden attribute set which are ignored by for /R. The option /A-D could be modified to /A-D-H to ignore hidden files.
The wildcard pattern contains a space character. For that reason the command DIR outputs just the full qualified file names of files which contain at least one space character in long file name. Short 8.3 file names cannot contain a space character.
The error message output by DIR if it cannot find at least one file name matching the wildcard pattern in the entire directory tree of current directory is suppressed by redirecting the error message from handle STDERR to device NUL.
Read the Microsoft documentation about Using command redirection operators for an explanation of 2>nul. The redirection operator > must be escaped with caret character ^ on FOR command line to be interpreted as literal character when Windows command interpreter processes this command line before executing command FOR which executes the embedded dir command line with using a separate command process started in background.
The command FOR respectively the cmd.exe instance processing the batch file captures all lines output by DIR to handle STDOUT of command process started in background. The processing of the list of full qualified file names starts when started cmd.exe closed itself after finishing execution of command DIR.
The list of file names to process is now completely in memory of the command process executing the batch file. The file renames done next by the loop cause multiply changes in file system, but that does not affect the list of file names processed by FOR as it is the case on using for /R. So there is surely no file name with a space in name skipped as the file system changes do not affect the processing of the files to rename.
FOR with option /F results by default in ignoring all empty lines. The command DIR does not output empty lines.
Next a non-empty line is split up by default into substrings using horizontal tab and normal space as string delimiters. That string splitting behavior is definitely not wanted here as the files to rename contain at least one space character. For that reason delims= is used to define an empty list of string delimiters which turns off the line splitting behavior completely.
There is by default ignored next a line of which first substring starts with default end of line character ;. But the command DIR with option /S outputs all file names with full path and it is therefore impossible that any full qualified file name starts with a semicolon. So it is not necessary to modify the default end of line character.
The full file name is assigned to loop variable I which is next assigned to the environment variable FullName. The file name with file extension without path is assigned to environment variable FileName. The environment variables are (re)defined while delayed environment variable expansion is disabled to process also file names correct containing one or more ! in name. If delayed expansion would be already enabled, each exclamation mark in file name assigned to loop variable I would be interpreted as beginning/end of a delayed expanded environment variable reference which of course is not wanted in this case.
Now delayed expansion is enabled to be able to rename the file using its full file name referenced delayed expanded and its new name without path with all spaces removed. Then the previous environment is restored which is necessary to avoid a stack overflow as there is much more done in background by setlocal EnableDelayedExpansion than toggling the state of delayed expansion and to process the next file name again in an environment with delayed expansion disabled. See this answer for details on what happens in background on each usage of the commands SETLOCAL and ENDLOCAL.
There is no guarantee that each file rename really works. The file rename fails if there is already a file or directory with new name in the directory of a file to rename. A file rename fails also if a file to rename is currently opened by an application which opened it with denying any access by another application.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
dir /?
echo /?
endlocal /?
for /?
ren /?
set /?
setlocal /?

Copying files from a list

I have a list of 4000 .tif images that I need copied from a folder containing 20,000+ images.
I am trying to use command prompt to do so by using code found from googling my problem.
the code is as follows:
for /f %a in H:\list.txt do copy %a H:\new
"H:\list.txt" is my list file
"H:\new" is where i want my files to be copied to
I am running this command in the file folder that contains the .tif files H:\Doc2 and I keep getting:
H:\list.txt was unexpected at this time.
What is causing the issue? Is my list not correctly set up?
It looks like this:
ABBA.TIF
ABBD.TIF
ABBQ.TIF
Do i need commas or colons after the file names?
H:\list.txt is a literal, you want to loop over each of the lines of the file. Check this out:
How do you loop through each line in a text file using a windows batch file?
for /F "tokens=*" %%A in (myfile.txt) do [process] %%A
Suggestion: tag this with "windows" as well.
Amir diagnosed your immediate problem - your code is missing the parentheses around the IN clause.
But you have another potential problem. Your list may include file names and or paths that contain spaces or other special characters. If so, then the name must be quoted.
The values in the list may already by quoted, or they may not. You can use the ~ modifier to strip any existing enclosing quotes that may or may not be there, and then explicitly add your own.
for /f %a in (H:\list.txt) do copy "%~a" H:\new
If you want to include the line in a batch file, then each % must be doubled as %%.

.bat file for renaming multiple folders

I am trying to write a batch script to rename multiple folders.
I would like to do something like below:
Rename all folders under the "Workspace" folder by appending my name in the end of the folder names
For example, rename:
Workspace/RiskFolder
Workspace/PNLFolder
to:
Workspace/RiskFolder_myname
Workspace/PNLFolder_myname
Is this possible?
You could use for to loop through each directory and rename it like so:
for /D %%f in (C:\path\to\Workspace\*) do rename "%%f" "%%~nxf_myname"
I tested this on Windows 7, but it should work at least as far back as with Windows XP.
What that does is this: for each directory in the path (within parenthesis), assign the directory name to the variable %%f, then rename the directory %%f to the name in the format you want (with your name attached). %%f holds the full pathname, which is fine for the first argument to the rename command, but for the second argument, we only want the filename+extension, thus the ~nx modifier prepended to our variable name.
By the way, when using this for loop on the command line (rather than part of a batch file) you only want to use one % instead of %% for your variable name. E.g. for %f in... instead of above.
See the following references from Microsoft for more details:
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/batch.mspx?mfr=true
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/for.mspx?mfr=true
You can use the following command within your batch file:-
for /F "usebackq tokens=*" %%a in (`dir /ad /b %1`) do ren %1\%%a %%a%2
This is the DOS 'for' command, which iterates over given set of items, and for each element in the set, performs the given action. For the given requirement, we need to do the following:-
1) Accept name of folder which contains sub-folders to be renamed(in your example, it is Workspace).
2) Accept the string to be appended to the end(in your example, it is your name).
3) List the names of sub-folders in the folder.
4) Rename by appending the string to original name.
Let's see how this for command accomplishes that. The format of 'for' command used here is:-
for /F ["options"] %variable IN (`command`) do command [command-parameters]
The command here assumes that the required parent directory name and string to be appended are passed on as command line parameters. These are represented by %1 and %2 (first and second parameters).
To enable us to issue a dos command to be evaluated, we need to use the /F option. The option string is :-
"usebackq tokens=*"
usebackq specifies backquouted string is a command to be evaluated.(Note that the dir command is enclosed within backquotes(`) )
tokens=* means to consider each line as a single token and pass to the command
To list the sub-directories in parent directory, we use the command:-
dir /ad /b %1
/ad displays only directories (ignores files)
/b displays it in bare format, i.e., only names are returned and date, time and other info are not.
%1 is the command line variable referring to parent directory.
%%a is the variable which receives the sub-directory name in each iteration. Double percentage symbol is required since we use it in a batch file, otherwise, just one is required (like %a)
Finally, we specify the action to be performed:-
ren %1\%%a %%a%2
%1\%%a constructs absolute path to sub-directory
%%a%2 append second command line parameter to original name
For more info on for command, type following in a command prompt:-
for /?
For another usage example, refer Loopy loops: The DOS way
No need for a batch file. This will work from the command line
for /d %D in ("Workspace\*") do ren "%D" "%~nxD_myName"
If you do use a batch file, then %D must become %%D
If there is no need to perform folder/file renaming with a batch file, you can also use the Bulk Rename Utility for Windows. Check this: http://www.bulkrenameutility.co.uk/Download.php
For /D %%f in (*) do rename "%%f" "%%fWhatEverNameYouLike"
pause
The pause is to see it! Make a cmd of it and put it in the folder that you want to rename all it's subfolders! They'll rename to each one folders name, plus the WhatEverNameYouLike

Renaming files overwrites part of the filename

I ahve a directory full of files, and I want to rename each of them to have TA_ in front of the original file name. file1.txt should be renamed to TA_file1.txt. What I am getting is TA_e1.txt instead.
ren "c:*.txt" "TA_*.txt" is the command I am trying to use.
The file names are all of various lengths, and no matter what I try, it always overwrites the first 3 characters of my file name....
A simple one liner would be:
for %i IN (*.txt) DO ren "%i" "TA_%i"
This loops over all files (*.txt) and passes their name in the %i variable to the ren command. ren can then use the %i content to expand it with your desired prefix.
The command will only work for files in the current directory. For more complex things you should write a batch file. Come back if you need help with that.

Resources