I have thousands of generated php files in a folder that are not necessary. They all having the same naming structure of 10 characters each example "rk9qiaLOaf.php".
But I don't want to delete all because the folder contains index.php,main.php such important files and I don't want them to be deleted.
Please, how can it be done to delete the files within a folder they all are having name count of 10 by a batch script. Thank you for reading my problem.
You could just use this from the Command prompt:
For /F "Delims=" %A In ('Where/F "C:\Users\Aung\Documents:??????????.php"') Do #Del %A
Just change the folder path as appropriate.
Edit
A recursive version, (could take a while).
For /F "Delims=" %A In ('Where/F /R "C:\Users\Aung" "??????????.php"') Do #Del %A
Once again just change the root folder, (use . for the current directory) as necessary.
You could use dir together with findstr to filter for the correct files:
dir /B /A:-D "*.php" | findstr /I "^..........\.php$"
Every dot . matches a single character. ^ and $ ensure to match the whole file name.
To delete the returned files, use this in command prompt cmd:
for /F "delims=" %F in ('dir /B /A:-D "*.php" ^| findstr /I "^..........\.php$"') do #del "%F"
Or this in a batch file:
for /F "delims=" %%F in ('dir /B /A:-D "*.php" ^| findstr /I "^..........\.php$"') do del "%%F"
And here is an alternative batch file approach relying on sub-string expansion:
#echo off
setlocal DisableDelayedExpansion
for /F "delims=" %%F in ('dir /B /A:-D "*.php"') do (
set "NAME=%%~nF" & set "EXT=%%~xF"
setlocal EnableDelayedExpansion
rem // Check whether file name is not longer than 10 characters:
if "!NAME!"=="!NAME:~,10!" (
rem // Check whether file name is longer than 9 characters:
if not "!NAME:~9!"=="" (
del "!NAME!!EXT!"
)
)
endlocal
)
endlocal
Related
I'm trying to pipe a string that contains folder paths to findstr to search for a particular part in the names of the given folders - or at least, that is what I'm planning to do.
I've got a source folder with files that have to be copied into multiple subfolders and after that, one of the copied files has to be renamed corresponding to the destination folder. If there already are files with the same names, they have to be overwritten. I am trying to achieve this via .bat-file using the following commands in my code:
pushd ..\..\destination_folder\
FOR /F "delims=" %%i in ('dir /AD /S /B^| findstr /I "._Modul_X$"') do copy ..\xxx\yyy\ressources\*.* %%i
& ren %%i\xxxx_Modul_X.BAT_TEMPLATE" "%%i_Modul_X.BAT_TEMPLATE
The copy-part seems to work, the rename-part does not and when it comes to overwriting the one file that has to be renamed after copying it (name conflict!), I'm pretty clueless how to do this (IF EXIST & DEL?).
If I understand the process you're attempting, then the following should do as you require, subject to my assumption that xxxx is a sequence of exactly four, digits (directory names), and characters (file names):
#Echo Off
SetLocal EnableExtensions
PushD "..\..\destination_folder" 2>NUL || GoTo :EOF
If Not Exist "..\xxx\yyy\resources\*.*" GoTo :EOF
For /F "Delims=" %%G In (
'Dir /B /S /A:D "????_Modul_X" 2^>NUL ^|%__AppDir__%findstr.exe^
/I /R "\\[0123456789][0123456789][0123456789][0123456789]_Modul_X"'
) Do (
For /F "Delims=" %%H In (
'%__AppDir__%where.exe /F "%%G":"????_Modul_X.BAT_TEMPLATE" 2^>NUL'
) Do Del /A /F %%H
Copy /Y "..\xxx\yyy\resources\*.*" "%%G" 1>NUL
For /F "Delims=" %%I In (
'%__AppDir__%where.exe /F "%%G":"????_Modul_X.BAT_TEMPLATE" 2^>NUL'
) Do If /I Not "%%~nxI" == "%%~nxG%%~xI" Ren %%I "%%~nxG%%~xI"
)
Please note that you will probably need to modify both instances of xxx\yyy\resources, (lines 5 and 14), as nobody really uses names like that, paying special attention to the spelling, I've used resources above, not ressources.
I have JSON files in different folders inside apps\*.json.
How to rename all of them by adding a suffix to the name?
a.json to a_file.json
b.json to b_file.json
Below is what I tried, but it is not producing the expected file names.
#echo off & setlocal EnableDelayedExpansion
for /f "delims=" %%i in ('dir /b *.json') do (
ren "%%i" "_file.json"
)
And how can I undo this operation?
a_file.json to a.json
The following commented batch script should do both:
add _file suffix if a non-empty parameter is supplied, and
remove _file suffix if a no parameter is supplied
(even in all subfolders if specified dir /b /S instead of dir /b):
#ECHO OFF
SETLOCAL EnableExtensions EnableDelayedExpansion
::: change next 3 lines to match current circumstances:
set "suffix=_file" suffix to add/remove
set "extens=json" file extension
set "folder=D:\test\SO\46404782" working directory
::: set working directory
pushd "%folder%"
if "%~1"=="" (
rem reverse
for /F "delims=" %%G in ('dir /b *%suffix%.%extens% 2^>NUL') do (
set "newname=%%~G"
set "newname=!newname:%suffix%.%extens%=.%extens%!"
ECHO ren "%%~fG" "!newname!"
)
) else (
rem add suffix
for /F "delims=" %%G in ('dir /b *.%extens% 2^>NUL') do (
ECHO ren "%%~fG" "%%~nG%suffix%%%~xG"
)
)
popd
Note that productive ren command is merely displayed using ECHO for debugging purposes.
Sample output:
==> D:\bat\SO\46404782.bat
ren "D:\test\SO\46404782\c_file.json" "c.json"
==> D:\bat\SO\46404782.bat 1
ren "D:\test\SO\46404782\a.json" "a_file.json"
ren "D:\test\SO\46404782\b.json" "b_file.json"
ren "D:\test\SO\46404782\c_file.json" "c_file_file.json"
==>
Resources (required reading, incomplete):
(command reference) An A-Z Index of the Windows CMD command line
(additional particularities) Windows CMD Shell Command Line Syntax
(%~nG, %~xG, %~1 etc. special page) Command Line arguments (Parameters)
(!newname:%suffix%.%extens%=.%extens%! etc.) Variable Edit/Replace
An easy solution for appending _file is running in command prompt window:
for /f "delims=" %i in ('dir /b *.json') do #ren "%i" "%~ni_file.json"
In a batch file % must be escaped with one more percent sign:
for /f "delims=" %%i in ('dir /b *.json') do #ren "%%i" "%%~ni_file.json"
%~ni or %%~ni references the file name without file extension and without path as explained by the help output on running in a command prompt window for /?.
Use additionally DIR option /s to process recursively all *.json files in current directory and all its subdirectories.
I am new to batch scripting . I need to delete all files in a folder that DOES NOT contains some word in the file
found this code
#echo off
setlocal
pushd C:\Users\admin\Desktop\bat
findstr /ip /c:"importantWord" *.txt > results.txt
popd
endlocal
So how i can WHITE list this files, and delete all other?
Or i think there is easy way with just check if !contains and delete
but i don`t know how?
Supposedly, this problem could be solved in a very simple way combining these findstr switches: /V that show results when the search string is not found, and /M that show just the name of the files; that is:
#echo off
setlocal
cd C:\Users\admin\Desktop\bat
for /F "delims=" %%a in ('findstr /ipvm /c:"importantWord" *.txt') do del "%%a"
Unfortunately, the combination of /V and /M switches don't properly work: the result of /V is based on lines (not files), so a modification in the method is needed:
#echo off
setlocal
cd C:\Users\admin\Desktop\bat
rem Create an array with all files
for %%a in (*.txt) do set "file[%%a]=1"
rem Remove files to preserve from the array
for /F "delims=" %%a in ('findstr /ipm /c:"importantWord" *.txt') do set "file[%%a]="
rem Delete remaining files
for /F "tokens=2 delims=[]" %%a in ('set file[') do del "%%a"
This method is efficient, particularly with big files, because findstr command report just the name of the files and stop searching after the first string match.
#echo off
setlocal
set "targetdir=C:\Users\admin\Desktop\bat"
pushd %targetdir%
for /f "delims=" %%a in ('dir /b /a-d *.txt') do (
findstr /i /p /v /c:"importantWord" "%%a" >nul
if not errorlevel 1 echo del "%%a"
)
popd
endlocal
Not really sure what you want to do with /pfiles - files containing non-ansi characters appear to return errorlevel 1for these. if not errorlevel 1 will echo the files that do not contain the required string - remove the echo to actually delete the file(s)
This should work:
#ECHO OFF
SETLOCAL EnableDelayedExpansion
SET "pathToFolder=C:\FolderToEmpty"
SET "wordToSearch=ImportantWord"
FOR /F "tokens=*" %%F IN ('dir %pathToFolder% /b *.txt') DO (
findstr /IP %wordToSearch% "%pathToFolder%\%%F">nul
IF !ERRORLEVEL!==1 (
DEL /Q "%pathToFolder%\%%F"
)
)
You will have to set the proper path to the folder you want to delete the files from and to replace ImportantWord with the substring you are looking for.
I would like to make a .bat file that will open the first file within a random folder/subfolders, in the same location as the .bat file.
The code I currently have only opens a random file.
#echo off
setlocal enableextensions disabledelayedexpansion
set "rootFolder=G:\Movies\Anime"
for /f "usebackq tokens=1,* delims=:" %%a in (`
cmd /q /v /e /c "for /f delims^= %%a in ('dir /a-d /s /b "%rootFolder%"') do echo(!random!:%%a"
^| sort 2^>nul
^| cmd /q /e /v /c "set /p ".^=" & echo(!.!"
`) do start "" "%%~b"
I also have a .bat file that generates a text file with a list of all folders in the same location. I'm not sure if it would be easier to reference that.
dir /b > Animelist.txt
Also if possible how to exclude it opening particular types of files such as jpegs / the other .bat file?
You can try with this
#echo off
setlocal enableextensions disabledelayedexpansion
set "rootFolder=%cd%"
set fileTypes= "*.avi" "*.mpeg" "*.mkv"
pushd "%rootFolder%" && (
for /f "usebackq tokens=1,* delims=:" %%a in (`
cmd /q /v /e /c "set p=&for /r %%a in (%fileTypes%) do if not !f!==%%~dpa (set f=%%~dpa&set /a ((%random% %% 16273^)+1^)*!random!&echo :%%~dpa)"
^| sort 2^>nul
^| cmd /q /e /v /c "set /p ".^=" && echo(!.!"
`) do pushd "%%~b." && (
for /f "delims=" %%c in ('
dir /b /a-d /on %fileTypes% 2^>nul
^| cmd /q /e /v /c "set /p ".^=" && echo(!.!"
') do start "" "%%~fc"
popd
)
popd
)
Decomposing the task in pieces
Configure where to search and what to search (first two set)
Change to the starting folder (pushd)
Execute a recursive search for the indicated file types and output the name of the folder where the file has been found (first cmd inside for /f
As more than one file can be found in the same folder, check that we will not output a duplicate element (if inside first cmd)
For each folder, generate a random number as a prefix (set /a) and output the folder (echo)
Sort the list on the random number (sort)
Get the first folder in the list. As the list is sorted on a random number, this folder has been random selected (second cmd inside for /f %%a)
Discard the random number and retrieve only the folder (the reason for the delims and tokens in the for /f %%a)
Change to the selected folder (pushd)
List the files of the indicated types inside the selected folder (dir)
From this list select only the first file (cmd)
Retrieve the selected file (for /f %%c)
Start the selected file (start)
Return to previous folder (popd)
Return to the starting folder (popd)
The random selection of a folder is unambiguous.
The first video file is a bit more difficult. If using dir with several extensions like #aschipfl suggested, this predetermines which extensions are looked for and found first.
The other way with excluding file types is more tedious without knowing which types might occur.
Here my batch Edited Streamlined some parts:
#echo off
setlocal enableextensions Enabledelayedexpansion
Set Cnt=0
Set "Exclude=.bat$ .cmd$ .jpg$ .jpeg$ .txt$"
Pushd "G:\Movies\Anime"
(Echo::: Numbered List of folders
For /f "delims=" %%F in (
'Dir /B/S/AD/ON'
) Do Set /A Cnt+=1&Echo:!Cnt!:%%F
)>DirList.txt
:: Get Random num 1..Cnt
Set /A RndDir=%Random% %% Cnt+1
:: Get random folder name
For /f "tokens=1,* Delims=:" %%F in (
'Findstr "^%RndDir%:" DirList.txt '
) Do Set "DirName=%%G"
Echo selected %RndDir% of %Cnt% = folder %DirName%
Pushd "%DirName%
Set "FileName"
For /f "Delims=" %%F in (
'Dir /B/A-D ^|findstr /i /V "%Exclude%"'
) Do If Not defined FileName Set "FileName=%%~F"
If defined FileName Start "" "%FileName%"
Popd
Popd
Goto :Eof
Can anyone help me create a batch file? Basically, my goal is to create a batch file that will keep the LATEST 7 .txt files (in other words, the newest) in the folder and subsequently delete the rest. That's IF there are more than 7 files in the folder.
The problem I'm having right now is the fact that the batch file that I have created deletes most of the files because their date is from a month or two or so. I want to keep the latest 7 files at all times no matter how old they are.
So this is what I have -
#echo off
setlocal enableextensions
rem ********************************************************************************
rem ******************************* LOCAL VARIABLES ******************************
rem ********************************************************************************
SET TargetDirectory="C:\TEMP\test"
SET No_of_fles_to_keep=7
SET count=0
set cnt=0
rem ********************************************************************************
cd /d %TargetDirectory%
REM timeout /T 500
for %%x in (*) do set /a count+=1
for %%A in (*.bat) do set /a cnt+=1
cd /d %TargetDirectory%
REM timeout /T 500
IF %count% gtr %No_of_fles_to_keep% forfiles -p %TargetDirectory% -s -m "*.txt" -d -%No_of_fles_to_keep% -c "cmd /c del #path"
echo %count%
echo File count = %cnt%
Any help is appreciated.
You can use DIR with /O-D to list the text files in descending timestamp order. FOR /F allows you to iterate over each file. SET /A is used to keep track of how many files have been listed so far. Now comes the tricky part.
Within a code block you normally need to use delayed expansion to work with the value of a variable that was set earlier in the same block. But delayed expansion can cause problems in a FOR loop if the FOR variable value contains !, and ! is valid in file names. I get around the problem by using SET /A to intentionally divide by 0 when the 7th file name has been read. This raises an error that causes the conditional code to execute that undefines the KEEP variable. From that point on, all remaining files are deleted.
#echo off
setlocal
set /a cnt=0
set "keep=7"
for /f "eol=: delims=" %%F in ('dir /b /o-d /a-d *.txt') do (
if defined keep (
2>nul set /a "cnt+=1, 1/(keep-cnt)" || set "keep="
) else del "%%F"
)
Update
Oh my goodness, I just realized there is a trivial solution. Just use the FOR /F SKIP option to ignore the first 7 entries after sorting by last modified date, descending.
for /f "skip=7 eol=: delims=" %%F in ('dir /b /o-d /a-d *.txt') do #del "%%F"
You don't even need a batch file. Just change %% to % if run from the command prompt.
The Batch file below use a simpler approach. It use findstr /N "^" command to number each file, then it just compare each number to keep first seven files and delete the rest...
#echo off
for /f "tokens=1* delims=:" %%a in ('dir /b /o-d *.txt ^| findstr /N "^"') do (
if %%a gtr 7 del "%%b"
)
Antonio
If you don't write DOS scripts frequently which I don't, here is a summation of what others noted.
Other examples here will need the batch file in the same folder that you're deleting from.
To delete from another path: (Notice you have to add the path twice to the search and to the delete)
SET targetDir="C:\Test\Files\"
for /f "skip=7 eol=: delims=" %%F in ('dir /b /o-d /a-d %targetDir%*.txt') do #del "%targetDir%""%%F"
Thanks #dbenham, #SmileyFace, #user2924127 and all others who helped bring the answers.
This will keep 7 latest .txt files and remove all other .txt files
Execute below command in same directory from which you want to delete files
On command prompt
for /f "skip=7 eol=: delims=" %F in ('dir /b /o-d /a-d *.txt') do #del "%F"
Inside batch script
for /f "skip=7 eol=: delims=" %%F in ('dir /b /o-d /a-d *.txt') do #del "%%F"