Batch remove parenthesis from file name - windows

After successfully removing a bunch of Google Drive Folder duplicates, some files retain a "filename(2)"name.
Is there a way to batch rename every file so the parenthesis and the number inside the parenthesis is gone?
That includes folders and sub-folders.

Try like this :
Create a file test.bat with the code below in it and replace the path to test in the var $path
#echo off
set $path="C:\Users\CN Micros\Desktop\PROGRAMMATION\test"
for /f "tokens=1-3 delims=^(^)" %%a in ('dir /b/a-d %$path%') do (
if exist %$path%\"%%a(%%b)%%c" echo ren %$path%\"%%a(%%b)%%c" "%%a%%c"
)
pause
Then run it in the CMD or by double clicking.
If the output is ok for you remove the echo
The program create 3 tokens : %%a = what's before the (), %%b What's inside the () and %%c what's after the ().
Then we arrange this 3 tokens to rename the files without the ().
If you have some file who have the same final name ie : "file(1)name", "file(2)name" --> "filename"
It will work only with the first one. If you have this case you have to add a counter at the end of file to be sure that they will be renamed.

This will create renfiles.bat.txt for you to examine in Notepad and then rename to .bat and execute if you are happy with it.
#echo off
dir /b /a-d *(*).* |find /i /v "%~nx0" |find /i /v "repl.bat" |repl "(.*)\(.*\)(\..*)" "ren \q$&\q \q$1$2\q" xa >"renfiles.bat.txt"
This uses a helper batch file called repl.bat - download from: https://www.dropbox.com/s/qidqwztmetbvklt/repl.bat
Place repl.bat in the same folder as the batch file or in a folder that is on the path.
Edit: This version will recurse through subdirectories:
#echo off
dir /b /s /a-d *(*).* |find /i /v "%~nx0" |find /i /v "repl.bat" |repl ".*\\(.*)\(.*\)(\..*)" "ren \q$&\q \q$1$2\q" xa >"renfiles.bat.txt"

#ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
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 (ECHO(REN "%%a" "!newname!%%~xa")
)
endlocal
)
GOTO :EOF
You'd need to set your required directory into sourcedir. I used u:\sourcedir which suits my testing.
The required REN commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(REN to REN to actually rename the files.

Related

Write a script to recursively list directories and files within it in Batch script

I am trying to write a batch script that recursively lists all directories and their files with *.js type in the below format:
For example, if I start with the C:\project directory
c:\project
project.js
project_time.js
c:\project\core
core.js
core_render.js
core_application.js
I tried to implement the above logic in code as follows:
#echo off
for /r %%f in (*.js) do (
echo %%f >> names.txt
)
pause
I was not able to print the directory under which the files are listed.
#echo off
setlocal disabledelayedexpansion
set "lastdir="
( for /r %%A in (*.js) do (
set "nextdir=%%~dpA"
setlocal enabledelayedexpansion
if /i not "!lastdir!" == "!nextdir!" (
rem Empty line and directory path.
if defined lastdir #echo(
#echo !nextdir!
)
endlocal
rem Filename.
#echo %%~nxA
set "lastdir=%%~dpA"
)
) > "names.txt"
The lastdir variable is to record the last directory path so it is echoed only once.
If lastdir is different to %%~dpA:
If lastdir is defined, then an empty line will be echoed.
Directory path of found file is echoed.
Filename is always echoed.
for modifiers dp is the drive and path. nx is the name and extension.
setlocal enabledelayedexpansion is used only where needed so paths with ! are not vulnerable.
I am not going to suggest a command line solution as it would be very long. Instead suggest use of tree command if the output format is suitable.
Here's an untested example, (I'm not expecting it to be quick if your base directory is large):
#Echo Off
(
For /F "Delims=" %%G In ('Dir /B /S /A:D "C:\Project" 2^> NUL') Do (
%__AppDir__%where.exe /Q "%%G":*.js 1> NUL 2> NUL
If Not ErrorLevel 1 (
Echo/
Echo %%G
For /F "EOL=| Delims=" %%H In ('%__AppDir__%where.exe "%%G":*.js')Do (
Echo %%~nxH
)
)
)
) 1> "names.txt"
Pause
If you prefer to run something from the Command Prompt, then try this version:
(For /F "Delims=" %G In ('Dir /B/S/AD "C:\Project" 2^>NUL')Do #(%__AppDir__%where.exe /Q "%G":*.js >NUL 2>&1&&(Echo/&Echo %G&For /F "EOL=|Delims=" %H In ('%__AppDir__%where.exe "%G":*.js')Do #Echo %~nxH)))>"names.txt"
Two simple ways to do this:
dir /S *.js
You get the answers, just as you requested.
FORFILES /S /M *.js /C "cmd /c echo #path"
You get complete path for every file.

How to rename only sub-folders without changing parent folder names

I have a folder containing several hundred sub-folders in the format Name, ID. Each of these folders contain several sub folders, some of which contain spaces in their names. I would like to rename only the sub folders and not the parent folders by replacing the spaces with underscores, e.g. C:\Location\John, 1234\My Documents to C:\Location\John, 1234\My_Documents.
I have tried modifying a piece of script I have found on here but it changes the parent folder as well
Here is the unedited code:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "StartFolder=C:\Tydelik"
cd /D %SystemRoot%
set "RenameError="
rem Rename all folders containing at least one space character in folder name.
for /F "delims=" %%I in ('dir "%StartFolder%\* *" /AD /B /S 2^>nul') do call :RenameFolder "%%I"
if defined RenameError echo/& pause
rem Restore initial environment and exit this batch file.
endlocal
goto :EOF
:RenameFolder
set "NewFolderName=%~nx1"
set "NewFolderName=%NewFolderName: =_%"
set "FolderPath=%~dp1"
if not exist "%FolderPath%" set "FolderPath=%FolderPath: =_%"
set "FullFolderName=%FolderPath%%~nx1"
if not exist "%FullFolderName%\" set "RenameError=1" & goto :EOF
for %%J in ("%FullFolderName%") do set "FolderAttributes=%%~aJ"
if "%FolderAttributes:~3,1%" == "h" %SystemRoot%\System32\attrib.exe -h "%FullFolderName%"
ren "%FullFolderName%" "%NewFolderName%" 2>nul
if errorlevel 1 goto ErrorFolderRename
if "%FolderAttributes:~3,1%" == "h" %SystemRoot%\System32\attrib.exe +h "%FolderPath%%NewFolderName%"
goto :EOF
:ErrorFolderRename
echo Error renaming folder "%FullFolderName%"
set "RenameError=1"
if "%FolderAttributes:~3,1%" == "h" %SystemRoot%\System32\attrib.exe +h "%FullFolderName%"
goto :EOF
As I said the expected output for each sub folder should be C:\Location\John, 1234\My_Documents instead of C:\Location\John, 1234\My Documents. Currently with the code I have, I get C:\Tydelik\John,_1234\My_Documents.
While Compo's solution renames folders "depth=2", this renames just the "leafes" (very last folders of a tree, "depth=last"). I kept your call approach to avoid delayed expansion and resulting possible problems (folder names with ! - unlikely in your situation, but one never knows...)
#echo off
setlocal
set "sourcedir=..\..\"
for /f "delims=" %%I in ('dir "%sourcedir%" /ad /b /s 2^>nul') do call :RenameFolder "%%I"
goto :eof
:RenameFolder
dir /ad /b /s "%~1" 2>nul | find /v "" >nul && goto :eof ::skip renaming, if a subfolder exists
set "leaf=%~nx1"
ECHO ren "%~1" "%leaf: =_%"
goto :eof
Note: for security reasons I disabled the ren command by just echoing it. If it works as intended, remove the ECHO.
Here's an example of what I think you're looking for, based upon the fact that you're interested only in renaming subdirectories of "C:\Tydelik\Name, ID", not any contained within those subdirectories:
#Echo Off
SetLocal DisableDelayedExpansion
Set "SourceDir=C:\Tydelik"
For /F "EOL=?Delims=" %%A In ('Dir /B/AD "%SourceDir%" 2^>NUL'
)Do Set "TargetDir="&For /F "EOL=?Delims=" %%B In (
'Dir /B/AD "%SourceDir%\%%A" 2^>NUL') Do (Set "TargetDir=%%B"
SetLocal EnableDelayedExpansion
If Not "!TargetDir: =!"=="!TargetDir!" (
Ren "%SourceDir%\%%A\%%B" "!TargetDir: =_!")
EndLocal)

Delete all folders and files except one file with specific name using .bat

I used the below code in .bat file in order to delete all files and folders inside “AutoCAD_Temp” except “parcel.dwg” but it didn’t work with me.
#echo
set exclude=/Parcel.dwg/
for %%a in (C:\inetpub\Temp_FME\AutoCAD_Temp) do (
if "!exclude:/%%~a/=!" equ "%exclude%"
(
echo "Deleting" %%~a
del "%%~a"
)
)
The folder Path: C:\inetpub\Temp_FME\AutoCAD_Temp
enter image description here
What might be the issue here?
I will be very appreciated for any help,
Lubna
If there is only one file to protect, all you need to do is to lock it
#echo off
setlocal enableextensions disabledelayedexpansion
rem Just to avoid having to retype paths, place info on variables
set "folder=C:\inetpub\Temp_FME\AutoCAD_Temp"
set "excluded=Parcel.dwg"
rem If the excluded file exist, we will need to lock it.
if exist "%folder%\%excluded%" ( set lock= ^< "%excluded%" ) else ( set "lock=" )
rem Change to requested folder, remove anything not locked and return
pushd "%folder%" && (
rmdir . /s /q %lock% 2>nul
popd
)
The reason for the file existence check is to avoid trying to lock a non existing file that will make the command fail, so, lock variable (holding the part of the final command that will lock the file for reading) is only defined if the file exists.
This is one line in PowerShell, for your consideration:
Get-ChildItem C:\inetpub\Temp_FME\AutoCAD_Temp\* -File -Exclude Parcel.dwg | Remove-Item -WhatIf
(If the output is correct, remove the -WhatIf parameter to remove the files.)
use findstr to exclude the file from the search using /v
#echo off
for /f "delims=" %a in ('dir /b "C:\inetpub\Temp_FME\AutoCAD_Temp" ^| findstr /vi "Parcel.dwg"') do (
echo "Deleting" %%~a
echo del "%%~a"
)
if you would like to predefine variables, simply:
#echo off
set "mypath=C:\inetpub\Temp_FME\AutoCAD_Temp"
set "exclude=Parcel.dwg"
for /f "delims=" %a in ('dir /b "%mypath%" ^| findstr /vi "%exclude%"') do (
echo "Deleting" %%~a
echo del "%%~a"
)

Remove specific folders with condition(s) using a batch file

I'm a newbie at batch scripting and couldn't figure out how to write up a batch file removing specific folders with conditions in c:\root.
Conditions:
If the folder names are other than "Paul", "Mike", "Daniel" and
"Pierre"
If the folder does not have a sub-folder or file
Action:
Delete that folder.
In my example, c:\root\test1 should be deleted with this batch file.
c:\root
c:\root\Paul
c:\root\Mike
c:\root\Mike\assignment
c:\root\Mike\assignment\assignment1.txt
c:\root\Daniel
c:\root\Daniel\exam
c:\root\Pierre
c:\root\Pierre\quiz.txt
c:\root\test1
c:\root\test2
c:\root\test2\test2.txt
Please let me know if anything is unclear.
Thank you very much.
You can start with this batch to test if the size of the folder equal to 0 (size=0) then we can remove it !
Just give a try for this code and if you get the output as you expected, just get rid of the echo
#echo off
setlocal disabledelayedexpansion
set "folder=%~1"
if not defined folder set "folder=%cd%"
for /d %%a in ("%folder%\*") do (
set "size=0"
for /f "tokens=3,5" %%b in ('dir /-c /a /w /s "%%~fa\*" 2^>nul ^| findstr /b /c:" "') do if "%%~c"=="" set "size=%%~b"
setlocal enabledelayedexpansion
If "!size!"=="0" Echo RD "%%~na"
endlocal
)
endlocal
pause
exit

Renaming files by folder hierarchy

I have many files with the following structure:
1969/ar/1.jpg
1969/ar/2.jpg
1969/he/1.jpg
1969/he/2.jpg
1969/en/1.jpg
1969/en/2.jpg
1970/ar/1.jpg
etc...
I want to rename all of them, with one command, to one directory, while their names reflect their original folder location.
1969_ar_1.jpg
1969_ar_2.jpg
1969_he_1.jpg
1969_he_2.jpg
1969_en_1.jpg
1969_en_2.jpg
1970_ar_1.jpg
etc...
Is it possible to do so with one command or a batch file?
Thanks!
You may do that to move the files to the base folder with this command-line:
for /R %a in (*) do #set f=%a& set f=!f:%cd%\=!& move "%a" !f:\=_!
Execute it from the folder that contain the 1969, 1970... folders. IMPORTANT!: Delayed Expansion must be active in order for this line to work, so you must previously activate it executing cmd.exe with /V switch this way: cmd /V.
For example:
>xcopy test backup /s
test\1969\ar\1.jpg
test\1969\ar\2.jpg
test\1969\en\1.jpg
test\1969\en\2.jpg
test\1969\he\1.jpg
test\1969\he\2.jpg
test\1970\ar\1.jpg
7 File(s) copied
>cd test
>dir /B
1969
1970
>for /R %a in (*) do #set f=%a& set f=!f:%cd%\=!& move "%a" !f:\=_!
>dir /B
1969
1969_ar_1.jpg
1969_ar_2.jpg
1969_en_1.jpg
1969_en_2.jpg
1969_he_1.jpg
1969_he_2.jpg
1970
1970_ar_1.jpg
Modify the line this way to move the files to another folder:
for /R %a in (*) do #set f=%a& set f=!f:%cd%\=!& move "%a" "\other\folder\!f:\=_!"
Or via this Batch file:
#echo off
setlocal EnableDelayedExpansion
for /R %%a in (*) do set f=%%a& set f=!f:%cd%\=!& move "%%a" "\other\folder\!f:\=_!"
Run this from the base of the tree that contains all *.jpg files.
Change the target folder to where you want the files to go:
Test it on some samples first.
#echo off
for /f "delims=" %%z in ('dir "*.jpg" /b /s /a-d ') do (
for %%a in ("%%~dpz%\.") do (
for %%b in ("%%~dpa\.") do (
ren "%%z" "%%~nxb_%%~nxa_%%~nxz"
move "%%~dpz\%%~nxb_%%~nxa_%%~nxz" "c:\target\folder"
)
)
)
pause
try this (look at the output and remove the word echo before move, if it is OK):
#echo off &setlocal
for /d %%i in (19* 20*) do (
cmd /c "for /r "%%i" %%j in (*.jpg) do #for %%k in ("%%~dpj.") do #echo move "%%~j" "%%i_%%~nk_%%~nxj""
)

Resources