Batch script to remove parentheses and spaces from all file names - windows

I have to manipulate dozens if not hundreds of images fairly often. When I get the images, it's often 1018u182012480d1j80.jpg type filenames, so I can select all of the images, and then hit 'F2' to rename them all to image (1).jpg | image (2).jpg | ... etc. Can someone write me a batch script to remove the parentheses and the spaces in the file names?
If possible, it'd be great if I didn't even have to open it up and edit the batch file to update the current dir, I.E, if it can just use %CD% or something to get the current folder, that would be awesome.
I don't understand batch files at all but here's one I found that will remove the parentheses, but I have to add the sourcedir.
#ECHO OFF
SETLOCAL
SET "sourcedir=C:\.." #Can we make this just find the location?
FOR /f "delims=" %%a IN (
'dir /b /s /a-d "%sourcedir%\*" '
) DO (
SET "name=%%~na"
SETLOCAL ENABLEDELAYEDEXPANSION
SET "newname=!name:)=!"
SET "newname=!newname:(=!"
IF "!name!" neq "!newname!" (
IF EXIST "%%~dpa!newname!%%~xa" (ECHO cannot RENAME %%a
) ELSE (REN "%%a" "!newname!%%~xa")
)
endlocal
)

The script should work if file names/paths does not contain any ! exclamation mark.
Supply a folder path as an argument (see sample calls below). This can be done even by file explorer's drag&drop feature (drag a folder, drop on batch). Read call /? or Command Line arguments (Parameters) for %~1 explanation.
Narrow to only .jpg files using "%sourcedir%\*.jpg" in FOR /f line.
#ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion
SET "sourcedir=%~1" supplied string
if NOT defined sourcedir SET "sourcedir=%CD%" current directory if nothing supplied
rem basic validity check
if NOT exist "%sourcedir%\*" (
echo wrong directory "%sourcedir%"
goto :next
)
FOR /f "delims=" %%a IN ('dir /b /s /a-d "%sourcedir%\*" ') DO (
SET "name=%%~na"
SETLOCAL ENABLEDELAYEDEXPANSION
rem remove ) right parenthesis
SET "newname=!name:)=!"
rem remove ( left parenthesis
SET "newname=!newname:(=!"
rem remove ↓ space(s)
SET "newname=!newname: =!"
IF "!name!" neq "!newname!" (
IF EXIST "%%~dpa!newname!%%~xa" (
ECHO cannot RENAME %%a
) ELSE (
rem operational RENAME command is merely ECHO-ed for debugging purposes
ECHO RENAME "%%a" "!newname!%%~xa"
)
)
ENDLOCAL
)
:next
rem pause to see output
pause
Sample call without argument - applies to the current directory:
d:\bat\SU> D:\bat\SO\43097467.bat
RENAME "d:\bat\SU\New Text Document.txt" "NewTextDocument.txt"
RENAME "d:\bat\SU\Files\ruzna pisma.png" "ruznapisma.png"
RENAME "d:\bat\SU\Files\volume control options.png" "volumecontroloptions.png"
RENAME "d:\bat\SU\Files\volume mixer.png" "volumemixer.png"
RENAME "d:\bat\SU\Files\1126981\ERKS 100004_thumb.jpg" "ERKS100004_thumb.jpg"
Press any key to continue . . .
Sample call with argument - applies to the supplied directory:
d:\bat\SU> D:\bat\SO\43097467.bat D:\test\43097467
RENAME "D:\test\43097467\image do - Copy (2).bmp" "imagedo-Copy2.bmp"
cannot RENAME D:\test\43097467\image do - Copy (3).bmp
RENAME "D:\test\43097467\image do - Copy (4).bmp" "imagedo-Copy4.bmp"
Press any key to continue . . .
Sample call, argument with spaces must be enclosed in a pair of double quotes:
d:\bat\SU> D:\bat\SO\43097467.bat "D:\bat\odds and ends\a b"
RENAME "D:\bat\odds and ends\a b\c d\my list_Utf8.txt" "mylist_Utf8.txt"
RENAME "D:\bat\odds and ends\a b\c d\e f\h i batch.bat" "hibatch.bat"
RENAME "D:\bat\odds and ends\a b\c d\e f\System locale.png" "Systemlocale.png"
Press any key to continue . . .
d:\bat\SU>

Related

compressing multiple files into bzip2

so i found this nice batch for window that would compress every file of the same extension in the same directory into bzip2 by dragging and dropping any of the files into it but i would like to take it further and make it that when i drag and drop a folder into it. it would compress all the files in it, including the sub-folders until it reaches the end. obviously i would guess it has something to do with looping with using %%d but i could not exactly figure it out.
#echo off
if [%1]==[] goto usage
for /f %%i in ("%1") do (
echo %%~di
echo %%~pi
echo %%~xi
set rootpath="%%~di%%~pi*%%~xi"
)
for %%f in (%rootpath%) do (
"C:\Program Files\7-Zip\7z.exe" a -tbzip2 "%%f.bz2" "%%f" -mx9
del "%%f" /s /f /q
)
echo Finished operations!
goto exit
:usage
echo You have to drag and drop a file on this batch script!
echo Sorry for the poor documentation, but if you'll want to use it, you have to edit the .bat file
echo The only thing you really need is to change the path to your 7-Zip installation
echo Then simply drag and drop a file in a folder you want to BZip2, and it'll do the rest automatically
:exit
pause
I share with you this helpful and well commented batch script posted by enteleform on superuser
I just modified this variable Set archivePath="%%~x.zip" to Set archivePath="%%~x.bz2"
How to make 7-zip do a whole bunch of folders
#Echo OFF
SetLocal EnableDelayedExpansion
Rem // 7-Zip Executable Path
Set sevenZip="C:\Program Files\7-Zip\7z.exe"
Rem // START: NewLine Variable Hack
Set newLine=^
Rem // END: NewLine Variable Hack !! DO NOT DELETE 2 EMPTY LINES ABOVE !!
Rem // Set ErrorLog Variables
Set errorCount=0
Set separator=--------------------------------------------------------
Set errorLog=!newLine!!newLine!!separator!!newLine!!newLine!
Set errorPrefix=ERROR #:
Set successMessage=All Files Were Successfully Archived
Rem // Loop Through Each Argument
SetLocal DisableDelayedExpansion
for %%x in (%*) do (
Rem // Use Current Argument To set File, Folder, & Archive Paths
SetLocal DisableDelayedExpansion
Set filePath="%%~x"
Set directoryFiles="%%~x\*"
Set archivePath="%%~x.bz2"
SetLocal EnableDelayedExpansion
Rem // Source Is A Folder
if exist !directoryFiles! (
Set sourcePath=!directoryFiles!
)
Rem // Source Is A File
if not exist !directoryFiles! (
Set sourcePath=!filePath!
)
Rem // Print Separator To Divide 7-Zip Output
echo !newLine!!newLine!!separator!!newLine!!newLine!
Rem // Add Files To Zip Archive
!sevenZip! A -TZIP !archivePath! !sourcePath!
Rem // Log Errors
if ErrorLevel 1 (
Set /A errorCount=errorCount+1
Set errorLog=!errorLog!!newLine!!errorPrefix!!sourcePath!
)
)
Rem // Print ErrorLog
if !errorCount!==0 (
Set errorLog=!errorLog!!newLine!!successMessage!
)
Echo !errorLog!!newLine!!newLine!!newLine!
Rem // Keep Window Open To View ErrorLog
pause
You could probably do that with a single line batch-file:
#For %%G In ("%~1")Do #If "%%~aG" GEq "d" (For /F Delims^= %%H In ('""%__AppDir__%where.exe" /R "%%~G" * 2>NUL|"%__AppDir__%findstr.exe" /EVIL ".bz2""')Do #"%ProgramFiles%\7-Zip\7z.exe" a -tbzip2 "%%~dpH%%~nH.bz2" "%%H" -mx9 -sdel -w >NUL 2>&1)&"%__AppDir__%timeout.exe" /T 3
If you'd like it over multiple lines for readability:
#For %%G In ("%~1") Do #If "%%~aG" GEq "d" (
For /F "Delims=" %%H In (
'""%__AppDir__%where.exe" /R "%%~G" * 2>NUL | "%__AppDir__%findstr.exe" /EVIL ".bz2""'
) Do #"%ProgramFiles%\7-Zip\7z.exe" a -tbzip2 "%%~dpH%%~nH.bz2" "%%H" -mx9 -sdel -w >NUL 2>&1
"%__AppDir__%timeout.exe" /T 3
)
These examples should only work if you drag and drop a directory onto it, or call it on the command line with a directory as the first argument.
#echo off
for /f %%i in ("%1") do (
echo %%~di
echo %%~pi
echo %%~xi
set rootpath="%%~di%%~pi*%%~xi"
)
for /R %%f in (*) do (
"C:\Program Files\7-Zip\7z.exe" a -tbzip2 "%%f.bz2" "%%f" -mx9 -x!"packall.bat"
del "%%f" /s /f /q
)
echo Finished operations!
goto exit
:usage
echo You have to drag and drop a file on this batch script!
echo Sorry for the poor documentation, but if you'll want to use it, you have to edit the .bat file
echo The only thing you really need is to change the path to your 7-Zip installation
echo Then simply drag and drop a file in a folder you want to BZip2, and it'll do the rest automatically
:exit
pause
Cheers to my friend Anya who found a solution, so the way it would work with the script above is that you make a batch file name it packall.bat
save it anywhere as it will delete itself at the end of the process.
when you want to compress bunch of files into bz2 you copy it and put it in inside a folder made with any name in your desktop.
make sure its name has no spaces nor its sub-folders as that may confuse batch and make it compress your desktop contents for some reason.
click on the batch, then it will compress all the files within the same folder its in and their sub-folders and automatically delete itself.
Video example:
http://billstuff.site.nfoservers.com/e79nwk69.mp4
IMPORTANT NOTE for some reason if there duplicate names of files with the same extension at sub-folders they will be deleted
Don't forget the folder and its sub-folder names should not have a space
Best of luck!

How to rename files in subfolder into a specific format

I have files named as RabcdYYMMKKACCOUNT.TXT in the Subfolders of a folder where YYMM is year, month this will change. KK is another identifier, I want all the files to be renamed to MSFKKDNB.ABC, the KK is the identifier in the input file.
Below is the one i tried and the result of it:
FOR /R %%f IN (*account.txt) DO REN "%%f" *dnb.abc
R00531706AUAccount.txt is renamed to R00531706AUAccount.txtdnb.abc
but the output should be MSFAUDNB.abc
This could be done for example with:
#echo off
setlocal EnableExtensions EnableDelayedExpansion
for /R %%I in (???????????account.txt) do (
set "FileName=%%~nI"
set "NewFileName=MSF!FileName:~9,2!DNB.abc"
if not exist "%%~dpI!NewFileName!" (
ren "%%~fI" "!NewFileName!" 2>nul
if not exist "%%~dpI!NewFileName!" echo Failed to rename file: "%%~fI"
) else (
echo Cannot rename file: "%%~fI"
)
)
endlocal
The file name of found account text file is assigned to environment variable FileName.
The new name for the file is created by concatenating the fixed parts MSF and DNB.abc with the 2 characters to keep from file name using string substitution and delayed expansion.
Next it is checked if a file with new name does not already exist. Is this the case the file renaming is done otherwise an error message is output.
After renaming the file it is checked if that was successful. A slightly different error is output if renaming failed for example because of a sharing violation.
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.
echo /?
endlocal /?
for /?
if /?
ren /?
set /?
setlocal /?
Read also the Microsoft article about Using Command Redirection Operators.
Try this:
#Echo Off
For %%A In ("*account.txt") Do (Set "_=%%~nA"
SetLocal EnableDelayedExpansion
Ren "%%A" "MSF!_:~-9,2!DNB.abc"
EndLocal)
I would probably do it the following way, provided that the files to rename are located in immediate sub-directories (YYMM) of the given root directory and nowhere else:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "_ROOT=." & rem // (specify path to the root directory)
for /D %%D in ("%_ROOT%\????") do (
for %%F in ("%_ROOT%\%%~nxD\R??????????Account.txt") do (
set "FDIR=%%~nxD" & set "FILE=%%~nxF"
setlocal EnableDelayedExpansion
ECHO ren "!_ROOT!\!FDIR!\!FILE!" "MSF!FILE:~9,2!DNB.abc"
endlocal
)
)
endlocal
exit /B
If you want to check whether both the sub-directory name and the year/month portion of the file names are purely numeric, you could use the following script:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "_ROOT=." & rem // (specify path to the root directory)
for /F "delims= eol=|" %%D in ('
dir /B /A:D "%_ROOT%\????" ^| ^
findstr "^[0123456789][0123456789][0123456789][0123456789]$"
') do (
for /F "delims= eol=|" %%F in ('
dir /B /A:-D "%_ROOT%\%%~nxD\R??????????Account.txt" ^| ^
findstr "^R....[0123456789][0123456789][0123456789][0123456789].."
') do (
set "FDIR=%%~nxD" & set "FILE=%%~nxF"
setlocal EnableDelayedExpansion
ECHO ren "!_ROOT!\!FDIR!\!FILE!" "MSF!FILE:~9,2!DNB.abc"
endlocal
)
)
endlocal
exit /B
If you want to check whether the sub-directory name matches the year/month (YYMM) portion of the file names, replace the pattern R??????????Account.txt by R????%%~nxD??Account.txt (for both scripts).
After having verified the correct output of either script, remove the upper-case ECHO commands to actually rename any files!
Basically, both scripts use sub-string expansion to extract the identifier part (KK) from the file names. Since there are variables set and read in the same block of code, delayed expansion is required for that. The second approach does not list the sub-directories and files by standard for loops, it uses the dir command, findstr to filter their names and a for /F loop to capture the resulting output for both sub-directories and files.

Read directories and split path

To list the directories I use this:
set folder=C:\temp
for /d %%a in ("%folder%\*") do (
echo %%~fa
)
To splith the file path I use this:
for %%f in (%MYDIR1%) do set myfolder=%%~nxf
echo %myfolder%
Now I want put both together:
#echo off
set folder=C:\Windows
for /d %%A in ("%folder%\*") do (
for %%d in (%%~fA) do set lastfolder=%%~nxf
echo %lastfolder%
)
All I get in thes result is %~nxf. I tried some things, but I didn't get a correct result. What I'm doing wrong?
What I don't understand in these examples is %~fA and %~nxf. Don't know where you can look up things like this.
Edit:
%~nxf to get file names with extensions
where F is the variable and ~n is the request for its name | Source
%~fI Expands %I to a fully qualified path name.
Now I modified my code with the new information:
#echo off
for /d %%A in ("%folder%\*") do (
for %%D in (%%~fA) do (
set lastfolder=%%~nxD
echo %lastfolder%
)
)
Now I get as result the last folder, but this is printed as many times as subfolders are existing. So I only get the last one. How can I iterate over each?
Solution:
Thanks to bgalea this is my solution:
#echo off
setlocal enabledelayedexpansion
set folder=C:\Windows
for /d %%A in ("%folder%\*") do (
for %%D in (%%~fA) do (
set lastfolder=%%~nxD
echo !lastfolder!
)
)
endlocal
Things in bracket are one line. Therefore you have to use !var! which you turn on with setlocal enabledelayedexpansion. See set /? and setlocal /?.
. is current directory and .. is parent directory.
So c:\temp\.. is the same as c:\
%~nx1 etc are documented in the call command's help - call /?
My answer here Trouble with renaming folders and sub folders using Batch has a list of command prompt punctuation.

Batchfile to search a string in the filepath

I wan to search for a specific string in the file-path and double that particular string.
Example: if my filepath is C:\Users\XXXX\Desktop\g%h.txt
I want to search and get the % symbol and I need to double it like this C:\Users\XXXX\Desktop\g%%h.txt
How to do this with batch file?
in batchfiles, you have to escape some special chars, so cmd knows NOT to treat them as "special". A percent-sign is escaped with another percent-sign:
#echo off
setlocal enabledelayedexpansion
for %%i in (*.txt) do (
set name=%%i
echo old name: !name!
set name=!name:%%=%%%%!
echo new name: !name!
)
Here is sample to match any txt that contain one or more %
#echo off
setlocal enabledelayedexpansion
for /f "delims=" %%i in ('dir /b /a-d *.txt ^|findstr /i "%%"') do ( set file=%%i
rem Here to remove every % in the name.
echo ren "!file!" "!file:%%=!"
)
exit /b 0
In batch files as it was mentioned above you have to escape % sign with another % sign and file names are no exception. So instead of set file=C:\Users\XXX\Desktop\r%h.txt you must use set file=C:\Users\XXX\Desktop\r%%h.txt.
I wrote a separate batch file that accept two arguments: the first one is naming pattern and the second one is a symbol that needs to be doubled. So, for instance, if you want to double character "r" in all .txt files in the current directory you type
<nameOfTheBatchFile> *.txt r in the command line. Or in your case you can go with
<nameOfTheBatchFile> C:\Users\XXX\Desktop\r%h.txt %
#echo off
setlocal enabledelayedexpansion
set "namingPattern=%1"
set "charToDouble=%2"
for %%i in (%namingPattern%) do (
set "curName=%%i"
set newName=!curName:%charToDouble%=%charToDouble%%charToDouble%!
if "!curName!" neq "!newName!" (
echo Renaming !curName! -^> !newName!
ren "!curName!" "!newName!"
)
)

Need a renaming script that strips filenames and adds folder name with increments

I need a script that will allow me to strip filenames to files that are placed within folders, and apply the folder names to the files, and add an incremental number to the end of each filename.
So the filenames would look something like this in their original state:
gdgeregdja34gtj.jpg
And then look like this after the script is executed:
foldername>foldername001.jpg
foldername>foldername002.jpg
I have this script, which allows the folder name to prefix any filename of files within folders. But it doesn't strip the filenames.
#echo off
pushd "Folder"
for /d %%D in (*) do (
for %%F in ("%%~D\*") do (
for %%P in ("%%F\..") do (
ren "%%F" "%%~nxP_%%~nxF"
)
)
)
popd
This will echo the rename commands to the screen, so if it does what you want then remove the echo to make it work.
Filenames with ! characters will not be renamed.
#echo off
setlocal enabledelayedexpansion
for /d /r %%a in (*) do (
set n=0
pushd "%%a"
for /f "delims=" %%b in (' dir /b /a-d 2^>nul ') do (
set /a n=n+1
set num=0000!n!
echo ren "%%b" "%%~nxa!num:~-4!%%~xb"
)
popd
)
pause

Resources