Batch script to delete files with specific length names - batch-file

I have tried del "C:\path\?????.txt" to delete files having name of length 5 characters(abcde.txt etc.).
It does delete the files with 5 char names but it also delete files having less than 5 char name (abc.txt,abcd.txt etc.)
Any help will be appreciated.

The following complete batch-file, which uses where.exe, will only match, and subsequently try to delete, files whose name contains exactly five characters and the .txt extension. (all you need to do is to use a ? to represent each character).
#SetLocal
#Set "PATHEXT="
#For /F "EOL=? Delims=" %%G In ('""%__AppDir__%where.exe" "%UserProfile%\Desktop\New":"?????.txt" 2> NUL"') Do #Del /A/F "%%G"
#EndLocal

There are a few ways to do this, this is one of them:
#echo off & setlocal enabledelayedexpansion
for /f "delims=" %%i in ('dir /b "%userprofile%\Desktop\New\*.txt"') do (
set "str=%%~i"
if "!str:~5!" == "%%~xi" del "%%~i" /Q /S
)

Related

Piping string with folders in variable to findstr - copy and rename files

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.

Batch script to delete files in folder that does not contain certain word

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.

How to remove all files having 10 characters in name with bat?

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

How to rename folders keeping first 8 Characters and removing the rest

I have some folders which says AA2017-123-TEXT and AA2017-124-TEXTS.
I'm trying to use batch to rename these file to AA2017-123 and AA2017-124 removing the text from the folder name. That is I want only the first 8 characters in a folder name.
I am using windows 7
To do exactly what have been asked for, namely splitting off a certain amount of characters, the following code snippet could be used (extracting the first 10 characters here for example):
for /F "delims=" %%D in ('dir /B /A:D "*"') do (
set "FOLDER=%%D"
setlocal EnableDelayedExpansion
move "!FOLDER!" "!FOLDER:~,10!"
endlocal
)
There are several ways to accomplish your task, IMO the simplest is using the hyphens as delimiters in a for loop.
In the cmd line
for /f "tokens=1,2* delims=-" %a in ('dir /B/ad *-*-*') do #echo ren "%a-%b-%c" "%a-%b"
In a batch
for /f "tokens=1,2* delims=-" %%a in ('dir /B/ad *-*-*') do echo ren "%%a-%%b-%%c" "%%a-%%b"
If the output looks ok remove the echo

Batch file that keeps the 7 latest files in a folder

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"

Resources