Delete .txt files in subfolders using batch script [duplicate] - batch-file

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Delete files in subfolder using batch script
I have to delete .txt files from a sub folder (with same name). My filepath is like as follows.
d:\test\test1\archive*.txt
d:\test\try\archive*.txt
d:\test\model\archive*.txt
I tried "del" command to delete the ".txt" files in above paths. But there are more than 100 folders in the folder "test". So it is very difficult to use "del" for each and every path.
Except the parent folder name of "archive" folder, everything remains the same for all the paths. So I guess there might be some easy way to delete the files using batch script.
Can anyone guide me whether there is any easy way to delete .txt files using batch script Or I have to repeat "del" for all 100 folders?

del /s *.txt
hope it helps.All the best mate

del /s *.txt will delete all TXT files in all subfolders of current working directory.
(But use that command carefully - wrong parent directory and you are throwing away all textfiles on your computer :) )

Edited
del /s d:\test\archive\*.txt
This should get you all of your text files
Alternatively,
I modified a script I already wrote to look for certain files to move them, this one should go and find files and delete them. It allows you to just choose to which folder by a selection screen.
Please test this on your system before using it though.
#echo off
Title DeleteFilesInSubfolderList
color 0A
SETLOCAL ENABLEDELAYEDEXPANSION
REM ---------------------------
REM *** EDIT VARIABLES BELOW ***
REM ---------------------------
set targetFolder=
REM targetFolder is the location you want to delete from
REM ---------------------------
REM *** DO NOT EDIT BELOW ***
REM ---------------------------
IF NOT DEFINED targetFolder echo.Please type in the full BASE Symform Offline Folder (I.E. U:\targetFolder)
IF NOT DEFINED targetFolder set /p targetFolder=:
cls
echo.Listing folders for: %targetFolder%\^*
echo.-------------------------------
set Index=1
for /d %%D in (%targetFolder%\*) do (
set "Subfolders[!Index!]=%%D"
set /a Index+=1
)
set /a UBound=Index-1
for /l %%i in (1,1,%UBound%) do echo. %%i. !Subfolders[%%i]!
:choiceloop
echo.-------------------------------
set /p Choice=Search for ERRORS in:
if "%Choice%"=="" goto chioceloop
if %Choice% LSS 1 goto choiceloop
if %Choice% GTR %UBound% goto choiceloop
set Subfolder=!Subfolders[%Choice%]!
goto start
:start
TITLE Delete Text Files - %Subfolder%
IF NOT EXIST %ERRPATH% goto notExist
IF EXIST %ERRPATH% echo.%ERRPATH% Exists - Beginning to test-delete files...
echo.Searching for .txt files...
pushd %ERRPATH%
for /r %%a in (*.txt) do (
echo "%%a" "%Subfolder%\%%~nxa"
)
popd
echo.
echo.
verIFy >nul
echo.Execute^?
choice /C:YNX /N /M "(Y)Yes or (N)No:"
IF '%ERRORLEVEL%'=='1' set question1=Y
IF '%ERRORLEVEL%'=='2' set question1=N
IF /I '%question1%'=='Y' goto execute
IF /I '%question1%'=='N' goto end
:execute
echo.%ERRPATH% Exists - Beginning to delete files...
echo.Searching for .txt files...
pushd %ERRPATH%
for /r %%a in (*.txt) do (
del "%%a" "%Subfolder%\%%~nxa"
)
popd
goto end
:end
echo.
echo.
echo.Finished deleting files from %subfolder%
pause
goto choiceloop
ENDLOCAL
exit
REM Created by Trevor Giannetti
REM An unpublished work
REM (October 2012)
If you change the
set targetFolder=
to the folder you want you won't get prompted for the folder.
*Remember when putting the base path in, the format does not include a '\' on the end.
e.g.
d:\test
c:\temp
Hope this helps

Related

Moving files using For Loop in Batch File programming

I am trying to create a batch-file to organize files by filetypes.
The idea is to move all files with extensions, except for the running script, into new directories, each named with the extension.
What code should I need to add or substitute for some of the code given below? This .bat file is in Documents folder and there are some files there.
#echo off
set x="%cd%\log.txt"
rem 'log.txt' contains the name of folder 'My Folder' and is already created in Downloads folder.
for %%a in (".\*") do (
for /F "tokens=*" %%i In ('type %x%') do (
if "%%~xa" neq "" if "%%~dpnxa" neq "%~dpnx0" (
if not exist "C:\Users\%username%\Downloads\%%i\%%~xa" md "C:\Users\%username%\Downloads\%%i\%%~xa"
move "%%a" "C:\Users\%username%\Downloads\%%i\%%~xa\"
)
)
)
pause
OUTPUT:
The system cannot find the file specified.
The system cannot find the file specified.
The system cannot find the file specified.
The system cannot find the file specified.
The system cannot find the file specified.
The system cannot find the file specified.
The system cannot find the file specified.
The system cannot find the file specified.
The system cannot find the file specified.
The system cannot find the file specified.
Press any key to continue . . .
This will create folders as C:\users\username\Downloads\.ext including the dot.
#echo off
set "x=%~dp0\log.txt"
rem 'log.txt' contains the name of folder 'My Folder' and is already created in Downloads folder.
for /F "delims=" %%i In ('type %x%') do (
if "%%~xi" neq "" if "%%~fi" neq "%~f0" (
md "%userprofile%\%%~xi" >nul 2>&1
move "%%~fi" "%userprofile%\Downloads\%%~xi\"
)
)
pause
If you do not want the dot. i.e C:\users\username\Downloads\ext
#echo off
setlocal enabledelayedexpansion
set "x=%~dp0\log.txt"
rem 'log.txt' contains the name of folder 'My Folder' and is already created in Downloads folder.
for /F "delims=" %%i In ('type %x%') do (
if "%%~xi" neq "" if "%%~fi" neq "%~f0" (
set "ext=%%~xi"
call set ext=!ext:.=!
md "%userprofile%\!ext!" >nul 2>&1
echo move "%%~fi" "%userprofile%\Downloads\!ext!"
)
)
pause
Note, I removed the %%i from the md command as it will create a folder with the name of the file, if that is what you wanted, just put it back.
Given my understanding of what you're trying to do, I would suggest something a little more like this:
#Echo Off
Set "DestDirName=My Folder"
If Exist "%~dp0log.txt" Set /P "DestDirName="<"%~dp0log.txt"
If Exist "log.txt" Set /P "DestDirName="<"log.txt"
For %%A In (*)Do If /I Not "%%A"=="%~nx0" If Not "%%A"=="log.txt" If Not "%%~xA"=="" (
Set "FileExtension=%%~xA"
SetLocal EnableDelayedExpansion
RoboCopy . "%UserProfile%\Downloads\%DestDirName%\!FileExtension:~1!" "%%A" /Mov>Nul
EndLocal
)
Pause
Lines 2, 3 and 4 will Set the name of the parent directory in Downloads which will hold the directories for your files to be moved to. I have used a new directory named My Folder as a backup just in case the file log.txt cannot be found in either the current directory, or that holding your running batch file. It currently selects the name in the following order of preference: 'current directory', 'batch file directory', 'My Folder'; you can switch lines 3 and 4, if you'd prefer the 'batch file directory' to take precedence over the 'current' directory. If log.txt is found, the Set /P command will set the variable DestDirName to the content of the first line of that file, please don't use doublequotes or a trailing backslash in that content.
The For loop will then proceed to move all files with extensions to directories named using their extension, without its leading period, held within the directory, from lines 2-4, and inside the users Downloads directory. When doing that it will not include itself or any file named log.txt.
BTW, it doesn't matter if the directory name string value of %DestDirName% already exists in Downloads, it will be created automatically if it doesn't.

Batch script to check if a folder exists. If yes, then copy a file from another folder to this folder

I am new to programming, with no background whatsoever.
I am creating a batch script which will create folders based on user input.
Then it will copy files from a shared server to the local folders that have been created.
I have the following script:
#ECHO OFF
REM *********************************************************************
REM **This will create directories and Copy Files for your project**
REM *********************************************************************
ECHO Plese enter the no. between 1 to 5 only
set /p input=[Please enter:1-Belgium, 2-Austria, 3-France, 4-Germany, 5-Greece]
if %input%==1 md BEL
if %input%==2 md AUT
if %input%==3 md FRA
if %input%==4 md DEU
if %input%==5 md GRE
if %input%==1 cd BEL
if %input%==2 cd AUT
if %input%==3 cd FRA
if %input%==4 cd DEU
if %input%==5 cd GRE
::ECHO Please enter the no. between 1 to 5 only
:END
set /p userinput=[Please enter your folder name]
mkdir %userinput%
cd %userinput%
set /p input=[Press 1 for 1.0, 2 for 2.0]
if %input%==1 md Folder1
if %input%==2 md Folder2
IF EXIST .\Folder1 xcopy "C:\ProgramFiles\kasras01\file2.txt"
All along, the code does well, until it comes to the part where I need to check if a folder exists. If it does, then I need to copy a file from another location to this folder.
But I am unable to get it to work. I think my syntax is incorrect.
How do I get it to work?
Grateful for any help.
The bottom line of your posted script should look more like this:
IF EXIST "Folder1" XCOPY "C:\ProgramFiles\kasras01\file2.txt" "Folder1\" /Y
Here also is a rewritten example using both Choice for the controlled input and Set /P with checks for the uncontrolled input:
#Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
CD /D "%~dp0" 2>Nul || Exit /B
REM **************************************************************************
REM ** This will create directories and copy a single file for your project **
REM **************************************************************************
Echo 1. Belgium&Echo 2. Austria&Echo 3. France&Echo 4. Germany&Echo 5. Greece
Choice /C 12345 /M "Which one"
If ErrorLevel 5 MD "GRE" 2>Nul & CD "GRE"
If ErrorLevel 4 MD "DEU" 2>Nul & CD "DEU"
If ErrorLevel 3 MD "FRA" 2>Nul & CD "FRA"
If ErrorLevel 2 MD "AUT" 2>Nul & CD "AUT"
If ErrorLevel 1 MD "BEL" 2>Nul & CD "BEL"
:DirPick
Echo(&Echo Please type your chosen directory name
Set /P "UserInput= then press enter: "
If Not Defined UserInput Echo Empty names are disallowed& GoTo DirPick
SetLocal EnableDelayedExpansion
For /F Tokens^=2^ Delims^=^\^/^:^*^?^"^|^<^>^ EOL^= %%A In ("[!UserInput!]"
) Do Echo Disallowed character detected& Set "UserInput=" & GoTo DirPick
EndLocal & MD "%UserInput%" 2>Nul & CD "%UserInput%"
Choice /C 12 /N /M "Press 1 for 1.0, 2 for 2.0"
XCopy "C:\ProgramFiles\kasras01\file2.txt" "Folder%ErrorLevel%\" /Y>Nul
The script is currently designed to use its own location as the base for the new directories etc. If you wish for a different base directory, change %~dp0 only on line 3 to the path you require.The XCopy command at the bottom currently has no checking mechanism, this means that if "C:\ProgramFiles\kasras01\file2.txt" doesn't exist, Folder[1|2] will not be created either! (Otherwise it would create Folder[1|2] and copy "C:\ProgramFiles\kasras01\file2.txt" into it.)
IF EXIST .\Folder1\ xcopy ...
Your code creates (eg) folder1 in the current directory, then looks for folder1 in the parent directory. Adding the \ looks for a directory only, not a file.
Are you aware that the xcopy will copy the file into the current directory, not the folder1 subdirectory?
xcopy "C:\ProgramFiles\kasras01\file2.txt" ".\folder%input%\"
should create and copy. You'd no doubt want to validate input is 1 or 2 first.
I need to check if a folder OR a file exists in a directory and I need to distinguish between them.
I found using \nul to be unreliable in some cases (Windows 10) - meaning that checking IF EXIST "%foldername%\nul" returned true regardless if there was a file or folder with the same name.
I found out that in my case, using IF EXIST "%foldername%\" (without nul) worked fine.
Snippet:
IF EXIST "%fname%" (
goto :f1
) ELSE (
goto :f2
)
:f1
IF EXIST "%fname%\" (
echo Folder with the same name already exists!
echo Cannot continue!
) ELSE (
echo File with the same name already exists!
echo Cannot continue!
)

Search for substring in folder names

I hope someone can help me with my problem.
There is a directory containing folders for every order, e.g.
L:\Med_Department\Orders\
L:\Med_Department\Orders\T0012345_AB100_CustomerA_site2
L:\Med_Department\Orders\T0012346_CD350-CustomerB site1
...
How can I get the full name of a folder by searching for the order number.
When I enter the order number for example:
T0012345
,
I want the script to store
T0012345_AB100_CustomerA_site2
in a variable so I can use it to create the folder for my new project instead of the order number.
The order number is unique and has the format Txxxxxxx . The rest of the folder name can be separated by underscore, blank space or other characters.
If the order number is not found (e.g. order number not entered correctly) the user should enter the order number again.
This is what I achieved so far.
I enter the order number and the script copies a template folder into my projects directory with the order number as folder name.
#Echo off
rem directories
set template= "N:\Documentation\New_folder_OrderNo-Type-Customer-site"
set dirOrder= "L:\Med_Department\Orders\"
SET dirProjects= "Z:\Projects\2016\"
rem input Order No.
echo Please enter the order number?
echo.
set /p OrderNo=OrderNo:
rem target directory
set dirNewProject=%dirProjects%%OrderNo%\
echo %dirnewProject%
pause
rem copy content from template into target directory
xcopy %template% %dirNewProject% /S /E /C /H /O /R /Y /D /V
rem open target directory
explorer %dirNewProject%
;exit
Thanks in advance.
something like this:
#Echo off
rem directories
set template= "N:\Documentation\New_folder_OrderNo-Type-Customer-site"
set dirOrder = "L:\Med_Department\Orders\"
SET dirProjects= "Z:\Projects\2016\"
:again
rem input Order No.
echo Please enter the order number?
echo.
set /p OrderNo=OrderNo:
if not exist "%dirOrder%%OrderNo%\" (
echo order %OrderNo% not found
goto :again
)
:: the rest of the script
:: ...
?
use a for to get the output of a command. Use dir with proper switches to do a wildcard search (Note: with dir wildcards do only work within the very last element of a path).
:again
set /p "OrderNo=OrderNo: "
set "folder=none"
for /f "delims=" %%a in ('dir /s /ad /b %dirOrder%%OrderNo%*') do set folder=%%a
if %folder% == none goto :again
echo found: %folder%
see for /? and dir /? for details
You can simply use for /D against the pattern %OrderNo%*. If there is folder whose name starts with %OrderNo% (there should be one only, if I got it right), dirNewProject is going to hold its path; if there is none, the variable is going to be empty. You can chek if [not] defined dirNewProject afterwards and jump to a :LABEL contitionally:
rem (skipping data entry part of script)
rem directory
set "dirNewProject="
for /D %%I in ("%dirProjects%\%OrderNo%*") do set "dirNewProject=%%I"
if not defined dirNewProject goto :LABEL
rem (skipping file copy part of script)
Example...(Untested)
#Echo Off
SetLocal
Rem directories
(Set template=N:\Documentation\New_folder_OrderNo-Type-Customer-site)
(Set dirOrder=L:\Med_Department\Orders)
(Set dirProjects=Z:\Projects\2016)
Rem exit if above directories do not exist
For %%a In (template dirOrder dirProjects) Do (If Not Exist "%%%%a%%\" Exit/B)
Rem make search dir current
If /I Not "%CD%" Equ "%dirOrder%" PushD %dirOrder%
:AskNum
Rem input Order No.
Echo(
Echo( Please enter the order number?
Echo(
Set/P "OrderNo=OrderNo: "
For /D %%a In ("%OrderNo%*") Do (Set OrderDir=%%~a)
If Not Defined OrderDir (Choice /C /M "Would you like to try again?"
If Errorlevel 2 Exit/B
GoTo :AskNum)
Rem new project directory
(Set dirNewProject=%dirProjects%\%OrderDir%)
Rem copy content from template to new project directory
If Not Exist "%dirNewProject%\" (
RoboCopy "%template%" "%dirNewProject%" /E /Copy:DATSO)
Rem open new project directory
Explorer "%dirNewProject%"

modify batch that copy in clipbrd older filename .mxf in folderA that are not in folderB

Thanks to foxidrive I have this code:
batch to copy in clipbrd filenameandpath of the older file in folderA except the same name in folderB
#echo off
:loop
set "d="
set "done="
set /p "d=Type source path (or press enter for current folder): "
if not defined d set "d=%cd%"
if not exist "%d%" echo Enter valid path - try again & goto :loop
cd /d "%d%"
for /f "delims=" %%a in ('dir *.mxf /b /od /a-d') do (
if defined done goto :EOF
if not exist "d:\folderB\%%~na.*" (
echo %%~fa|clip >nul
set done=1
)
)
OK, it work very well, thanks!
now I should like to do this:
and then the batch have to nename a file o:\temp.avi with the filename choosed by the batch (and putted into the clipbrd) example: if the batch have choose (into folderA) C0001.mxf, it have to rename o:\temp.avi --------> C0001.avi
Add the line in the middle between the other two.
echo %%~fa|clip >nul
ren "o:\temp.avi" "%%~nxa.avi"
set done=1
Read the help section on how Stack Overflow works: https://stackoverflow.com/tour

Delete files in subfolder using batch script

I have to delete files from a sub folder with a same name. My file path is like as follows.
d:\test\test1\archive\*.txt
d:\test\try\archive\*.txt
d:\test\model\archive\*.txt
I tried deleting using del command in batch script.
But there are more than 100 folders with in the folder "test". So it is very difficult to use del for each and every path.
Except for the parent folder name of "archive" folder, everything remains the same for all the paths. So I guess there might be some easy way to delete the files using batch script.
Can anyone guide me whether there is any easy way to delete the files using batch script? Or i have to repeat del for all 100 folders?
You can use the /s switch for del to delete in subfolders as well.
Example
del D:\test\*.* /s
Would delete all files under test including all files in all subfolders.
To remove folders use rd, same switch applies.
rd D:\test\folder /s /q
rd doesn't support wildcards * though so if you want to recursively delete all subfolders under the test directory you can use a for loop.
for /r /d D:\test %a in (*) do rd %a /s /q
If you are using the for option in a batch file remember to use 2 %'s instead of 1.
Use powershell inside your bat file
PowerShell Remove-Item c:\scripts\* -include *.txt -exclude *test* -force -recurse
You can also exclude from removing some specific folder or file:
PowerShell Remove-Item C:/* -Exclude WINDOWS,autoexec.bat -force -recurse
Moved from the closed topic
del /s d:\test\archive*.txt
This should get you all of your text files
Alternatively,
I modified a script I already wrote to look for certain files to move them, this one should go and find files and delete them. It allows you to just choose to which folder by a selection screen.
Please test this on your system before using it though.
#echo off
Title DeleteFilesInSubfolderList
color 0A
SETLOCAL ENABLEDELAYEDEXPANSION
REM ---------------------------
REM *** EDIT VARIABLES BELOW ***
REM ---------------------------
set targetFolder=
REM targetFolder is the location you want to delete from
REM ---------------------------
REM *** DO NOT EDIT BELOW ***
REM ---------------------------
IF NOT DEFINED targetFolder echo.Please type in the full BASE Symform Offline Folder (I.E. U:\targetFolder)
IF NOT DEFINED targetFolder set /p targetFolder=:
cls
echo.Listing folders for: %targetFolder%\^*
echo.-------------------------------
set Index=1
for /d %%D in (%targetFolder%\*) do (
set "Subfolders[!Index!]=%%D"
set /a Index+=1
)
set /a UBound=Index-1
for /l %%i in (1,1,%UBound%) do echo. %%i. !Subfolders[%%i]!
:choiceloop
echo.-------------------------------
set /p Choice=Search for ERRORS in:
if "%Choice%"=="" goto chioceloop
if %Choice% LSS 1 goto choiceloop
if %Choice% GTR %UBound% goto choiceloop
set Subfolder=!Subfolders[%Choice%]!
goto start
:start
TITLE Delete Text Files - %Subfolder%
IF NOT EXIST %ERRPATH% goto notExist
IF EXIST %ERRPATH% echo.%ERRPATH% Exists - Beginning to test-delete files...
echo.Searching for .txt files...
pushd %ERRPATH%
for /r %%a in (*.txt) do (
echo "%%a" "%Subfolder%\%%~nxa"
)
popd
echo.
echo.
verIFy >nul
echo.Execute^?
choice /C:YNX /N /M "(Y)Yes or (N)No:"
IF '%ERRORLEVEL%'=='1' set question1=Y
IF '%ERRORLEVEL%'=='2' set question1=N
IF /I '%question1%'=='Y' goto execute
IF /I '%question1%'=='N' goto end
:execute
echo.%ERRPATH% Exists - Beginning to delete files...
echo.Searching for .txt files...
pushd %ERRPATH%
for /r %%a in (*.txt) do (
del "%%a" "%Subfolder%\%%~nxa"
)
popd
goto end
:end
echo.
echo.
echo.Finished deleting files from %subfolder%
pause
goto choiceloop
ENDLOCAL
exit
REM Created by Trevor Giannetti
REM An unpublished work
REM (October 2012)
If you change the
set targetFolder=
to the folder you want you won't get prompted for the folder.
*Remember when putting the base path in, the format does not include a '\' on the end.
e.g.
d:\test
c:\temp
Hope this helps
I had to complete the same task and I used a "for" loop and a "del" command as follows:
#ECHO OFF
set dir=%cd%
FOR /d /r %dir% %%x in (archive\) do (
if exist "%%x" del %%x\*.txt /f /q
)
You can set the dir variable with any start directory you want or used the current directory (%cd%) variable.
These are the options for "for" command:
/d For directories
/r For recursive
These are the options for "del" command:
/f Force deletes read-only files
/q Quiet mode; suppresses prompts for delete confirmations.
del parentpath (or just place the .bat file inside parent folder) *.txt /s
That will delete all .txt files in the parent and all sub folders. If you want to delete multiple file extensions just add a space and do the same thing. Ex. *.txt *.dll *.xml

Resources