Batch file that deletes all but the last 10 per file name - windows

I have multiple folders with multiple files with the same name and then a timestamp. Example:
foo_2017.01.16.png
foo_2017.01.15.png
foo_2017.01.14.png
bar_2017.01.16.png
bar_2017.01.15.png
bar_2017.01.14.png
file_2017.01.16.png
file_2017.01.15.png
file_2017.01.14.png
What I'm needing to do is create a batch file that will parse out only the name before the _timestamp and keep the last 10 of each file name. I'm not very well versed in batch and could really use some help here. The Date Modified for every file is the same, so I cannot just say keep only the last 10 days, otherwise I could handle that.
EDIT:
I have a batch file that deletes files in a specific folder older than 28 days that looks like the following, I just do not know how to modify it to iterate through for each file name specifically and to not go by Date Modified:
/c echo #FILE
forfiles -p "C:\workspace\SeleniumTestResults" -s -m *.* /D -28 /C "cmd /c del #path"
Again, this batch is definitely not my area

#echo off
setlocal
REM create some files for testing:
break>foo_2017.01.16.png
break>foo_2017.01.15.png
break>foo_2017.01.14.png
break>bar_2017.01.16.png
break>bar_2017.01.15.png
break>bar_2017.01.14.png
break>file_2017.01.16.png
break>file_2017.01.15.png
break>file_2017.01.14.png
dir *.png
set keep=2
for /f "delims=_" %%a in ('dir /b *.png') do (
for /f "skip=%keep% delims=" %%b in ('dir /b /o-n "%%~a*.png"') do del "%%b"
)
dir *.png

Related

BATCH - Use FOR loop on directory files, ordered on Creation date/time

I'm wanting to order files in a directory based on date of creation (or at least, last modified).
I have this code:
FOR /R "directory" %%F IN (*.filetype) DO echo "command" "%%F" > "another\directory\%%~nF.tsv"
...which runs a for loop on files in no particular order (alphabetically?).
What I want to be able to do is:
FOR /R "direcotry\*.filetype" %%F IN ('dir /o-d /b "directory"') DO echo "command" "%%F" > "another\directory\%%~nF.tsv"
The lower code doesn't work, but you may see what I mean.
I'm proficient in BASH but not in BATCH
The key is dir /o-d /b "drive:\directory\*.filetype", which orders by creation date (reverse order), and then spits out only the file name -- but I don't know how to work this into a for loop for taking file names, and then running a command on them.
FOR /F "delims=" %%F IN ('dir /o-d /tc /b /s "directory\*.filetype"') DO echo "command" "%%F" >> "another\directory\%%~nF.tsv"
for/f to process a "file" of text.
"delims=" to turn tokenising off so the entire line of "output" from the dir is assigned.
/tc to use creation date (o/[-]d omitted = alphabetical order from an NTFS drive, storge-order on FAT)
/s to add subdiectories
>> to append to output file.
OR
...DO "command" "%%F"
to execute the command directly without creating the file.
Due to the limitation mentioned in the comment to the other answer, here is a potential workaround leveraging PowerShell:
#For /F "Delims=" %%A In (
'Powershell "(GCI "directory" -R *.filetype|Sort CreationTime -Des)|%%{$_.Fullname}"'
) Do #"command" "%%A">"another\directory\%%~nA.tsv"
Obviously adjusting directory, filetype, "command" and another\directory as required

shell script to rename a file name based on another file name

I have 2 files in my folder. One is "TEST ONE.txt", the other is "LEARN NEW.vcd".
I need to create a batch script to rename the *.txt using the *.vcd.
So the Batch script should rename the "TEST ONE.txt file" to "LEARN NEW.txt".
I have only one file with txt and one file with vcd extension in my folder C:\DEV folder.
I tried using the following script but it does not pick up the full name of the vcd extension and drops everything after the spaces - so I just get LEARN.txt :(
#echo ON
CD "C:\DEV folder"
setlocal enabledelayedexpansion
for /F %%A in ('dir /b *.vcd') do (
set xname= %%~nA
ren *.txt !xname!.txt
)
Thanks - db
It appears that the default in FOR /F may be to only take one (1) token. You can force it to take all using tokens=*. Quoting is important.
#echo ON
CD "sub"
setlocal enabledelayedexpansion
for /F "usebackq tokens=*" %%A in (`dir /b *.vcd`) do (
set xname=%%~nA
ren "*.txt" "!xname!.txt"
)
Just in case someone stumbles across this the way I did, there is a more elegant solution that I was forced to devise because I wanted it to go through multiple sub-directories, rather than run it one directory at a time. It is:
forfiles /S /M *.vcd /C "cmd /c rename *.txt #fname.txt"
Use your file extensions of choice.

Batch File delete newest file

How do you all delete the newest file in a folder using batch script?
All results I have found ONLY show how to delete the oldest files or delete them after N days.
Links are : Batch file to delete files older than N days and Batch Script to delete oldest folder in a given folder
Thank you
for /F %%a in ('dir /B /O-D /A-D %the_directory%') do echo("%the_directory%\%%a"&goto deldone
:deldone
would be my approach. It rudely escapes from the for loop having deleted the first filename encountered in a sorted-in-reverse-date-order (/o-d) list.
This saves having to read the entire list. Not such a problem with a few files, but can be a pain with thousands.
The required DEL command is merely ECHOed for testing purposes. After you've verified that the command is correct, change ECHO(DEL to DEL to actually delete the files.
I would do this:
#echo off
set latest=
set the_directory=your_directory
for /F %%a in ('dir /B /OD /A-D %the_directory%') do set latest=%%a
del %the_directory%\%latest%
run dir on files only, with sorting on modification date. Then loop and keep last echoed file. Delete it (replace by echo to test!)
The following code snippet does what you want:
set "FILE="
pushd "\path\to\folder" || exit /B 1
for /F "eol=| delims=" %%F in ('
dir /B /A:-D /O:D /T:C "*.*"
') do (
set "FILE=%%F"
)
if defined FILE del "%FILE%"
popd
The dir command returns files only (/A:-D) sorted by date in ascending order (/O:D) using the creation date (/T:C), which are located in \path\to\folder and match the pattern *.*.
The for /F loop walks through all the files returned by dir and assigns its name to variable FILE, overwriting it in each iteration, hence the final value is the name of the newest file.
The del command finally deletes the found file. The if query covers the case when no files are found in the given location.
Here is a slightly modified variant as recommended by Magoo's comment, which might be a bit more performant than the aforementioned one:
set "FILE="
pushd "\path\to\folder" || exit /B 1
for /F "eol=| delims=" %%F in ('
dir /B /A:-D /O:-D /T:C "*.*"
') do (
if not defined FILE set "FILE=%%F"
)
if defined FILE del "%FILE%"
popd
This avoids multiplicately overwriting of variable FILE by querying whether it has already been defined. Note the reversed sort order of dir here.
However, the approach shown in Magoo's answer is still better in performance.

Win cmd rar each file separately while keeping the name, with spaces

I'm using Windows and I have a huge list of files
something nextthing.ext
other something.ext
banana apple.ext
I'm trying to generate the following:
something nextthing.rar
other something.rar
banana apple.rar
I've done some research and I couldn't find how to do this. I know WinRAR has a built in way to do this, but it won't let me keep the names. It just renames them to Foldername1.rar, Foldername2.rar ....
I tried using the following command line:
for /f "delims=|" %f in ('dir /b "C:\Users\Adam\
Desktop\Files"') do rar a %f *.rar
However, it doesn't generate all files and they seem to be named wrongly...
For example, what should be banana apple.rar becomes banana.rar and apple.rar
Okay, found how....
#echo off &setlocal
set "path=C:\Program Files\WinRAR;%path%"
:indiv
echo(
echo(
FOR %%i IN (*) do (
rar a "%%~ni.rar" "%%~i" || echo Error building archive!
)
You can use in a command prompt window to compress each file in a directory into a separate archive:
for /f "delims=" %f in ('dir "%USERPROFILE%\Desktop\Files" /B /A-D') do "%ProgramFiles%\WinRAR\Rar.exe" a -ep1 -idcdp "%~nf.rar" "%f"
Important are the double quotes around %f as some file names contain 1 or more spaces and in this case the file names must be enclosed in double quotes.
Above command for usage in a batch file:
#echo off
for /f "delims=" %%f in ('dir "%USERPROFILE%\Desktop\Files" /B /A-D') do "%ProgramFiles%\WinRAR\Rar.exe" a -ep1 -idcdp "%%~nf.rar" "%%f"
This command ignores subfolders because of /A-D. It compresses only each file in directory Files on desktop of current user.

Windows Batch folder exist and folder not exist

Have a need where we need to delete zip files that exist under a specific folder at 100 days old. All other zip files in the other folders, we can delete that are 30 days old. This would be easy if the files were a specific name, unfortunately we can only do this by folder name.
In the end result we will be using one of these techniques with FORFILES as we don't have to do a lot of logic programming in script.
Searched and did find how to do this and works OK, but the processing of the script is very slow.. Pretty much at this point, everything in the "NOT" somefolder condition is what takes quite a while to complete. Have done this with VBScript and PowerShell, but really want to get back to Batch Scripting for this.
BAT script to search directory for folders that match an input name
and as dbenham admits, again this is very slow. Also, did not like the fact that it does not show all folders in the "not" condition for the ones it does not find
He also states, that if you want to do extensive file/folder searching redirecting to a output file, maybe the best solution
This does work, but does not show the "not found" or the folders it would list..
dir /s /a-d c:\windows\*system32* >nul && (echo found it) || (echo not found)
This works to find all folders with system32 on a drive
dir /b /ad /s "c:\system32"
This works to look for folders that DO HAVE system32 within the results which are pretty quick too
FOR /f "tokens=*" %%G IN ('dir /b /ad /s c:\ ^| findstr /I /C:"system32"') DO echo %%G
We want to show all folders that DO NOT HAVE system32 within and in testing and redirecting to result.txt file, it created a 11.9MB file and will take quite a while to complete especially on a whole drive
FOR /f "tokens=*" %%G IN ('dir /b /ad /s c:\ ^| findstr /I /V /C:"system32"') DO echo %%G
How do I search for the directory of a file given its name using a batch script?
Not quite sure about this one
for /r c:\ %%F in (system32) if exist "%%F" echo %%~dpF
Playing around we get
For /F %%A IN('dir /s /a-d "c:\windows\*system32*") do && (echo found it) || (echo not found)
Are there any other ideas or Suggestions out there?
This will search in c:\files and below, and delete zip files by the following criteria:
In the folder called Special folder it will delete them if they are 100 days or older
otherwise it will delete them if they are 30 days or older.
Any zip file in the folders below the Special folder will be deleted at 30 days and older.
Test it before use.
#echo off
for /r "c:\files" %%a in (*.zip) do (
for %%b in ("%%~dpa\.") do (
if /i "%%~nxb"=="Special folder" (
forfiles /p "%%~dpa." /m "%%~nxa" /d -100 /c "cmd /c del #path"
) else (
forfiles /p "%%~dpa." /m "%%~nxa" /d -30 /c "cmd /c del #path"
)
)
)
pause

Resources